are Hierarchical SIngletons in Java possible?
- by Zach H
I've been toying with an interesting idea (No idea if I'll include it in any code, but it's fun to think about)
Let's say we have a program that requires a large number of classes, all of a certain subclass. And those classes all need to be singletons. Now, we could write the singleton pattern for each of those classes, but it seems wasteful to write the same code over and over, and we already have a common base class. It would be really nice to create a getSingleton method of A that when called from a subclass, returns a singleton of the B class (cast to class A for simplicity)
class A{
public A getSingleton(){
//Wizardry
}
}
class B extends A{
}
A blargh = B.getSingleton()
A gish = B.getSingleton()
if(A == B)
System.out.println("It works!")
It seems to me that the way to do this would be to recognize and call B's default constructor (assuming we don't need to pass anything in.) I know a little of the black magic of reflection in Java, but i'm not sure if this can be done.
Anyone interested in puzzling over this?