Singleton Design Pattern

COMP 310  Java Resources  Eclipse Resources

(Back to Design Patterns)

Summary: Singletons model situations where only a single instance of a class can exist in a system.

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.

Figure 1: A Singleton can be implemented by either exposing a public, static, final field or accessor method.
Two Examples of a Singleton Implementation
Singleton examples

The public static field 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 this 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 public static method 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 static field technique simpler, if it can be implemented in the language of choice. However, the static method 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 this technique.

 

 


Originally published in Connexions (CNX): https://web.archive.org/web/20120506004033/http://cnx.org/content/m26426/latest/

© 2023 by Stephen Wong