Design Patterns, Singleton

Singleton, is probably, the most controversial object oriented design pattern. Many people even consider it an antipattern.

It is used when one and only one instance of a class should exist per JVM (or classloader).

I personally believe it is a useful pattern and with some care it can definitely solve more problems than it can introduce ( http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking–clever–but-broken.html ).

There are quite a few implementations of the Singleton pattern, most of which are designed around JVM’s and Java’s intricacies. My favourite one is the lazily initialized one, using the holder idiom. The benefits of this implementation are that the class will only be initialized if and when needed and the thread safety is guaranteed by the language itself.

A sample implementation is the following:

For the complete example along with a unit test please see: Design Pattern Examples