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?
Technically, I see no reason why something similar to this can’t be done. Your exact scheme won’t work because your
getSingletonisstatic(even though you fail to declare it as such) so it can’t tell which class it’s being called for. Change it tostatic A getSingleton(Class cls), and it might be workable.However, is this really that much of a win over having a one-liner
getSingletonin each derived class?For starters, your one
getSingletonreturnsA, so if someone calls it forB, they get back anAand have to downcast to use it as aB.Also, the scheme isn’t exactly transparent.
Sure, it’s fun to think about, but I’d look for more compelling reasons before doing this in any production system.