First, I'm sorry for the question title but I can't think of a better one to describe my problem. Feel free to change it :)
Let's say I have this abstract class Box which implements a couple of constructors, methods and whatever on some private variables. Then I have a couple of sub classes like BoxA and BoxB. Both of these implement extra things.
Now I have another abstract class Shape and a few sub classes like Square and Circle.
For both BoxA and BoxB I need to have a list of Shape objects but I need to make sure that only Square objects go into BoxA's list and only Circle objects go into BoxB's list.
For that list (on each box), I need to have a get() and set() method and also a addShape() and removeShape() methods.
Another important thing to know is that for each box created, either BoxA or BoxB, each respectively Shape list is exactly the same. Let's say I create a list of Square's named ls and two BoxA objects named boxA1 and boxA2. No matter what, both boxA1 and boxA2 must have the same ls list.
This is my idea:
public abstract class Box {
// private instance variables
public Box() {
// constructor stuff
}
// public instance methods
}
public class BoxA extends Box {
// private instance variables
private static List<Shape> list;
public BoxA() {
// constructor stuff
}
// public instance methods
public static List<Square> getList() {
List<Square> aux = new ArrayList<Square>();
for(Square s : list.values()) {
aux.add(s.clone()); // I know what I'm doing with this clone, don't worry about it
}
return aux;
}
public static void setList(List<Square> newList) {
list = new ArrayList<Square>(newList);
}
public static void addShape(Square s) {
list.add(s);
}
public static void removeShape(Square s) {
list.remove(list.indexOf(s));
}
}
As the list needs to be the same for that type of object, I declared as static and all methods that work with that list are also static. Now, for BoxB the class would be almost the same regarding the list stuff. I would only replace Square by Triangle and the problem was solved. So, for each BoxA object created, the list would be only one and the same for each BoxB object created, but a different type of list of course.
So, what's my problem you ask? Well, I don't like the code... The getList(), setList(), addShape() and removeShape() methods are basically repeated for BoxA and BoxB, only the type of the objects that the list will hold is different.
I can't think of way to do it in the super class Box instead. Doing it statically too, using Shape instead of Square and Triangle, wouldn't work because the list would be only one and I need it to be only one but for each sub class of Box.
How could I do this differently and better?
P.S: I could not describe my real example because I don't know the correct words in English for the stuff I'm doing, so I just used a box and shapes example, but it's basically the same.