Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
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 need to work with resource that must exist strictly in one instance, e.g., global logger, connection pool or application configuration.
When need to provide convenient access point to object from different parts of code, without need to pass it through all levels.
Singleton is often considered as "more manageable" alternative to global variables, as it can be tested and encapsulates logic.
Private constructor
Prevents creating objects via new, forcing all users to use special access method.
Static access method
Usually called getInstance(). On first call creates instance and saves it, on subsequent calls returns already created object.
Static variable
Stores reference to single class instance.
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!"
getInstance() method checks if object already exists. If not — creates, if yes — returns existing.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).
Read more about Singleton here.