Singleton
Ensures a class has only one instance and provides a global point of access to it.
errorThe Challenge
Some resources—database connections, configuration managers, logging services—should exist as a single shared instance. Creating multiple instances wastes memory, causes inconsistent state, and can lead to race conditions in concurrent environments.
check_circleThe Solution
Make the constructor private and provide a static method that always returns the same instance. On first call, the instance is created; on subsequent calls, the existing instance is returned. Thread-safe variants use double-checked locking or language-level guarantees.
Architecture Overview
Rendering diagram...
Implementation
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor prevents direct instantiation
}
static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
// Business methods
doSomething(): void {
console.log("Singleton method called");
}
}
// Usage
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // trueReal-World Analogy
“Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).”