Sometimes, a class must have exactly one instance, e.g., a class that maps to a physical resource
How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible but doesn’t keep you from instantiating multiple objects.
A better solution is to make the class itself responsible for keeping track of its sole instance, i.e., a Singleton
Singleton: Applicability
Use the Singleton pattern when:
There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code
Singleton: Structure
Singleton: Participants
Singleton
Defines an instance operation that lets clients access a unique instance
The instance (in C++) is a static member function
Class may be responsible for creating a unique instance (typical)
Singleton: Consequences
Controls access to the sole instance
In place of global variables, and avoids polluting the global namespace
The Singleton class can be subclassed
Once in place, you can change your mind and allow more than one instance
More flexible than static member functions, which are not polymorphic (i.e., cannot make them virtual)