Singleton Pattern
Summary
- The Singleton pattern ensures that a class is instantiated only once and that all requests are directed to that one and only object.
- The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object.
- In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.
Class diagram: (see Singleton Pattern code review)
Usage
Use the Singleton pattern when:
- You need to ensure there is only one instance of a class.
- Controlled access to that instance is essential.
- You might need more than one instance at a later stage.
- The control should be localized in the instantiated class, not in some other mechanism.