views:

826

answers:

4

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?

+1  A: 

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:

"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.

Aaron Digulla
+3  A: 

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.

erickson
Even if generics were reified it still wouldn't work without other modifications to the language. For instance, statics would still be shared by all parameterisations of the same class.
Tom Hawtin - tackline
With reified generics, I can envision an implementation that reflects on the actual type to find a class member variable. I might speculate, but I guess I should draw the line at meta-speculation.
erickson
+2  A: 

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.

Reed Copsey
A: 

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.

ConcernedOfTunbridgeWells
A good singleton is three lines of code. The class declaration, the instance declaration and initializer, and the private constructor.
erickson