Singleton
Category
Creational pattern
Problem
Ensure a class has only one instance in the entire application and provide a global point of access to it. Useful for coordinating system-wide actions, such as configuration management or connection pooling.
Solution
- Make the class constructor private to prevent external instantiation
- Create a static method that returns the single instance
- Lazily initialize the instance on first access
- Use thread-safe mechanisms (locking, double-checked locking) for concurrent access
Structure
- Singleton:
- Private static instance variable
- Private constructor
- Public static
getInstance()method - Thread-safe initialization mechanism
Key Benefits
- Controlled access — Exactly one instance, no ambiguity
- Global access point — Available from anywhere in the application
- Lazy initialization — Instance is created only when first needed
- Reduced memory footprint — Only one instance exists for the application lifetime
Trade-offs
- Violates Single Responsibility Principle — Manages its own lifecycle
- Difficult to test — Global state makes unit testing harder; requires mocking
- Thread-safety complexity — Requires careful handling in concurrent environments
- Can become a hidden dependency — Makes it hard to see where the instance is used
When to Use
- Exactly one instance of a class is needed (e.g., database connection pool, configuration manager, logging service)
- Lazy initialization is needed to defer expensive object creation
- The instance must be accessible from anywhere without passing references