Singleton Pattern
Singleton (Singleton) is creational design pattern that guarantees class will have only one single instance, accessible from anywhere in program. This is especially useful for resources that must be unique within application: configuration, logger, cache, etc.
Why Singleton is Needed:
Singleton provides centralized way to manage resources and provides universal "entry point" (instance) to its functionality.
At same time it guarantees that more than one object instance won't be created during program execution.
When to Apply "Singleton"?
Limited Resource
When need to work with resource that must exist strictly in one instance, e.g., global logger, connection pool or application configuration.
Simplifying Access
When need to provide convenient access point to object from different parts of code, without need to pass it through all levels.
Replacing Global Variables
Singleton is often considered as "more manageable" alternative to global variables, as it can be tested and encapsulates logic.
How Does Singleton Work?
-
Private constructor
Prevents creating objects vianew, forcing all users to use special access method. -
Static access method
Usually calledgetInstance(). On first call creates instance and saves it, on subsequent calls returns already created object. -
Static variable
Stores reference to single class instance.
Example (TypeScript)
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor prevents creating objects from outside
console.log("Initializing single instance...");
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod(): void {
console.log("Calling method on singleton!");
}
}
// Usage example
const obj1 = Singleton.getInstance(); // Initialization and creation
const obj2 = Singleton.getInstance(); // Returns already created instance
console.log(obj1 === obj2); // true — both reference same object
obj1.someMethod(); // "Calling method on singleton!"
- instance — static property storing reference to single object.
- constructor is closed to external calls.
- When calling
getInstance()method checks if object already exists. If not — creates, if yes — returns existing.
Advantages
- Single access point: Convenient to manage object that must exist in one instance.
- Easier to test than global variables: Can "substitute" Singleton in tests, though this still isn't as simple as with regular dependency.
- No duplication: Guaranteed that object won't be created again.
Disadvantages
- Global state: Singleton effectively replaces global variables, which with excessive use can complicate testing and application logic.
- Harder to refactor: If tests or new features suddenly need more instances, refactoring from Singleton can be problematic.
- Implicit dependencies: Code that uses Singleton often doesn't explicitly indicate dependencies in interface, but simply calls getInstance(), which can hide work logic.
Attention:
Excessive use of singletons can lead to strong code coupling and complicate testing. Before introducing Singleton, think about patterns like IoC (Inversion of Control) or DI (Dependency Injection).
When to Use
- Unique resources: Logger, system configuration, class for working with global cache.
- Synchronization: When object must "manage" resource accessible from different threads (if talking about backend), and need to guarantee "single" storage.
Source
Read more about Singleton here.
- refactoring.guru - patterns and refactoring
- patterns.dev - patterns