Ensure a class has a single instance and provide a global access point to it. A single shared resource is required (for example, config, cache). You
Singleton
Overview
Ensure a class has a single instance and provide a global access point to it.
When to use
- A single shared resource is required (for example, config, cache).
- You need lazy initialization and controlled access.
Java example
TypeScript example
Pros and cons
Pros:
- Controlled access to a single instance.
- Lazy initialization possible.
Cons:
- Global state makes tests harder.
- Hidden dependencies can spread.
Common pitfalls
- Using Singleton as a default for shared state.
- Thread-safety issues in lazy initialization.
- Hard-coded instance creation that blocks testing.