Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Purpose and Use Case
Use the Singleton pattern when a class in your application must have only a single instance available to all clients (for example, a database connection object, a centralized logger, or a global configuration manager).
Pattern Structure
Regardless of the programming language (TypeScript, PHP, Python, C++, etc.), the conceptual structure of the pattern relies on three pillars:
- Private constructor: Prevents other objects from using the
newoperator directly. - Private static attribute: Stores the reference to the single created instance.
- Public static method (
getInstance): Acts as a global access point that initializes the instance on first request and returns it on subsequent calls.
Cargando diagrama...
How It Works
- Request: The client calls
Singleton.getInstance(). - Verification: The class checks whether the static variable
instancealready holds an object. - Lazy initialization: If the instance does not exist (
nullorundefined), it privately invokes the constructor and assigns it. - Return: Returns the existing instance, ensuring a single shared object across the entire application.
Real-World Implementation Examples
// LoggerService.ts — Centralized logging service
class LoggerService {
private static instance: LoggerService;
private logs: string[] = [];
private constructor() {}
public static getInstance(): LoggerService {
if (!LoggerService.instance) {
LoggerService.instance = new LoggerService();
}
return LoggerService.instance;
}
public log(message: string): void {
const timestamp = new Date().toISOString();
const entry = `[${timestamp}] ${message}`;
this.logs.push(entry);
console.log(entry);
}
public getHistory(): string[] {
return [...this.logs];
}
}
// Usage anywhere in the application:
const logger1 = LoggerService.getInstance();
logger1.log("User logged in successfully");
const logger2 = LoggerService.getInstance();
logger2.log("HTTP 200 response received");
// Both references point to the exact same instance and shared log history
console.log(logger1 === logger2); // true