Singleton
21 Mar 2022Intent
Ensure a class only has one instance, and provide a global point of access to it.
Applicability
Use 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 subclassis, and client should be able to use an extended instance without modifying their code.
Structure
Participants
- Singleton: defines an instance operation that lets clients access it's unique instance. May be responsible for creating it's own unique instance.
Collaborations
Clients access a Singleton instance solely through Singleton's Instances operation.
Consequences
The singleton pattern has several benefits:
- Controlled access to sole instance.
- Reduced name space.
- Permits refinement of operations and representations.
- Permts a variable number of instances.
- More flexible than class operations.
Sample Code
Related Patterns
Many patterns can be implemented using the Singleton pattern - Abstract Factory, Builder, Prototype.