Singleton Design Pattern using TypeScript
The Singleton design pattern ensures that a class has only one instance
and provides a global point of access to it. This pattern is useful when you want to limit the number of instances of a class to one.
Here’s an example of the Singleton design pattern implemented in TypeScript:
class Singleton {
// Holds the single instance of the class
private static instance: Singleton;
// Private constructor ensures the class can't be instantiated from outside
private constructor() {
// Initialize any properties here
}
// Static method to provide access to the single instance
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
// Example method for demonstration
public showMessage(): void {
console.log("Hello from the Singleton instance!");
}
}
// Usage
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
// Output: Hello from the Singleton instance!
singleton1.showMessage();
// Output: true (Both are the same instance)
console.log(singleton1 === singleton2);
Applications
The Singleton design pattern is commonly used in scenarios where you need to ensure that a class has only one instance, such as:
- Database connections
- Configuration settings
- Logger instances
- Caching mechanisms
- Thread pools
- Print spoolers
- Event managers