The Singleton design pattern is used to represent an object in a situation where only a single instance of that object can exist. Situations where this might arise include objects representing null or empty, centralized broker objects, centralized accumulator objects, etc.
There are two possible techniques for implementing Singletons in object-oriented systems. Both techniques are illustrated in the diagram below:
Below, the class Singleton is the class for which only a single instantiation is desired. Both techniques rely on using a private constructor to prevent clients from creating more instantiations of Singleton. The single instance is held as the static class variable, ONLY.
The technique at the top of the diagram can be implemented in Java but not in C++ because Java is capable of automatically initializing class members while C++ cannot. In the top technique, the client accesses the solitary instance via the public, static class member Singleton.ONLY. This field is accessible by any object that has access to the Singleton class.
The technique at the bottom of the diagram can be implemented in any language. Here, the client obtains a reference to the sole instance by calling the public, static class method Singleton.getONLY(). This method is accessible by any object that has access to the Singleton class. The static class field ONLYis not automatically initialized. Instead, its initialization occurs the first time that Singleton.getONLY() is called by the client.
The top technique simpler, if it can be implemented in the language of choice. However, the bottom technique has an advantage when the Singleton class is large, expensive and/or time-intensive to instantiate. Initialization of the singleton instance only occurs if and when it is needed in the bottom technique.