How can I make a family of singletons?
- by Jay
I want to create a set of classes that share a lot of common behavior. Of course in OOP when you think that you automatically think "abstract class with subclasses". But among the things I want these classes to do is to each have a static list of instances of the class. The list should function as sort of a singleton within the class. I mean each of the sub-classes has a singleton, not that they share one. "Singleton" to that subclass, not a true singleton. But if it's a static, how can I inherit it?
Of course code like this won't work:
public abstract A
{
static List<A> myList;
public static List getList()
{
if (myList==null)
myList=new ArrayList<A>(10);
return myList;
}
public static A getSomethingFromList()
{
List listInstance=getList();
... do stuff with list ...
}
public int getSomethingFromA()
{
... regular code acting against current instance ...
}
}
public class A1 extends A
{
...
}
public class A2 extends A
{
...
}
A1 somethingfromA1List=(A1) A1.getSomethingFromList();
A2 somethingfromA2List=(A2) A2.getSomethingFromList();
The contents of the list for each subclass would be different, but all the code to work on the lists would be the same.
The problem with the above code is that I'd only have one list for all the subclasses, and I want one for each. Yes, I could replicate the code to declare the static list in each of the subclasses, but then I'd also have to replicate all the code that adds to the lists and searches the list, etc, which rather defeats the purpose of subclassing.
Any ideas on how to do this without replicating code?