Sometimes it's important to have only one instance for a class.
For example, in a system there should be only one window manager or only one print spooler.
Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
The singleton pattern involves only one class which is required to instantiate itself and to make sure it creates not more than one instance.
At the same time it provides a global point of access to that instance.
In this case the same instance can be accessed from anywhere, making it impossible to directly invoke the constructor each time.
The implementation involves
- a static member in the "Singleton" class,
- a private constructor and
- a static public method that returns a reference to the static member.
The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients.
getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.
The upcoming modules introduce you to many more patterns.
In the next module, you will have a chance to work with another creational pattern, the "factory method" pattern.