Should I use a collection here?
- by Eva
So I have code set up like this:
public interface IInterface {
public void setField(Object field);
}
public abstract class AbstractClass extends JPanel implements IInterface {
private Object field_;
public void setField(Object field) {
field_ = field;
}
}
public class ClassA extends AbstractClass {
public ClassA() {
// unique ClassA constructor stuff
}
public Dimension getPreferredSize() {
return new Dimension(1, 1);
}
}
public class ClassB extends AbstractClass {
public ClassB() {
// unique ClassB constructor stuff
}
public Dimension getPreferredSize() {
return new Dimension(42, 42);
}
}
public class ConsumerA {
public ConsumerA(Collection<AbstractClass> collection) {
for (AbstractClass abstractClass : collection) {
abstractClass.setField(this);
abstractClass.repaint();
}
}
}
All hunky-dory so far, until
public class ConsumerB {
// Option 1
public ConsumerB(ClassA a, ClassB b) {
methodThatOnlyTakesA(a);
methodThatOnlyTakesB(b);
}
// Option 2
public ConsumerB(Collection<AbstractClass> collection) {
for (IInterface i : collection) {
if (i instanceof ClassA) {
methodThatOnlyTakesA((ClassA) i);
else if (i instanceof ClassB) {
methodThatOnlyTakesB((ClassB) i);
}
}
}
}
public class UsingOption1 {
public static void main(String[] args) {
ClassA a = new ClassA();
ClassB b = new ClassB();
Collection<AbstractClass> collection = Arrays.asList(a, b);
ConsumerA consumerA = new ConsumerA(collection);
ConsumerB consumerB = new ConsumerB(a, b);
}
}
public class UsingOption2 {
public static void main(String[] args) {
Collection<AbstractClass> collection = Arrays.asList(new ClassA(), new ClassB());
ConsumerA = new ConsumerA(collection);
ConsumerB = new ConsumerB(collection);
}
}
With a lot more classes extending AbstractClass, both options get unwieldly. Option1 would make the constructor of ConsumerB really long. Also UsingOption1 would get long too. Option2 would have way more if statements than I feel comfortable with. Is there a viable Option3? If it helps, ClassA and ClassB have all the same methods, they're just implemented differently. Thanks for slogging through my code!