Singleton
creational
Ensures a class has only one instance and provides a global point of access to it.
Intent
The Singleton pattern ensures that a class has only one instance throughout the application lifecycle and provides a global access point to that instance.
Motivation
Some classes should have exactly one instance. For example, a configuration manager, a connection pool, or a logging service. The Singleton pattern provides a way to ensure that only one instance of such classes exists and provides a global access point to it.
Structure
The Singleton class declares a static method getInstance() that returns the same instance of its own class. The Singleton's constructor is made private to prevent direct construction calls with the new operator.
Participants
- •Singleton - declares a static getInstance() method that returns the unique instance
- •Client - accesses the Singleton instance through the getInstance() method
Pros
- ✓Controlled access to the sole instance
- ✓Reduced namespace pollution
- ✓Permits refinement of operations and representation
- ✓Lazy initialization is possible
Cons
- ✗Difficult to test due to global state
- ✗Violates Single Responsibility Principle
- ✗Can mask bad design
- ✗Requires special treatment in multithreaded environment
Use Cases
Configuration management
Connection pooling
Logging services
Cache management
Thread pools
Device drivers
Implementation Tips
Considerations
- •Ensure thread safety in concurrent environments
- •Consider lazy vs eager initialization
- •Be careful with serialization/deserialization
- •Watch out for reflection attacks
Tips
- •Use private constructor to prevent instantiation
- •Store the instance in a private static field
- •Provide a public static method to get the instance
- •Consider using modules for singleton behavior in modern JavaScript/TypeScript