In C++, I understand that it is possible to create a Singleton base class using templates. It is described in the book, Modern C++ Design, by Andrei Alexandrescu.
Can something like this be achieved in Java?
In C++, I understand that it is possible to create a Singleton base class using templates. It is described in the book, Modern C++ Design, by Andrei Alexandrescu.
Can something like this be achieved in Java?
Yes, but all approaches have their flaws. They are either expensive (using synchronized
) or make testing impossible (final static
).
See the links to the right:
http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java
http://stackoverflow.com/questions/86654/whats-wrong-with-singleton
http://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch
"State of the art" is to use a container or factory which creates the singletons as needed and keeps them in some kind of cache. See Spring, Guice, etc.
Because Java's generics are not reified, it isn't possible to implement a generalized Singleton in the same way. Because the generic types are "erased" from the compiled code, the singleton would have to be explicitly initialized at runtime.
The upshot is, a Singleton template would not provide much value in Java.
I have yet to see a satisfactory solution for this in Java. There are many examples using templates in C++ or generics in .NET, but Java's generics implementation has some limitations with static members that make this difficult.
The best option I've seen is to use a static HashMap, and a factory class. This allows you to make a single factory that can serve multiple Singletons of any class.
For an implementation, see this post.
In 1997 I tried to do this with JDK 1.0.2 and came to the conclusion that it was not possible to make an inheritable singleton. As far as I can tell Java has not gained any new features that would allow this.
However, doing this manually does not involve a lot of boilerplate code, maybe 10 lines or so per class. If you need to make some sort of anonymous factory mechanism the singletons could implement an interface with placeholders for the instantiation protocol.