The Singleton design pattern ensures that a class has only one instance and provides a global access point to it. This pattern is particularly useful when you want to control access to shared resources, such as database connections or configuration files.
Main Features of the Singleton
- A single shared instance
- Controlled access through a static method
- Private constructor to prevent external instantiation
Implementation in TypeScript
Below is an example of how to implement a Singleton class in TypeScript:
class Singleton {
private static instance: Singleton;
// Private constructor to prevent direct instantiation
private constructor() {
console.log('Singleton instance created');
}
// Static method to get the instance
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public doSomething(): void {
console.log('Singleton method called');
}
}
// Usage
const singleton1 = Singleton.getInstance();
singleton1.doSomething();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // true
Code Explanation
private static instance
: holds the single instance of the class.private constructor
: prevents creation of new instances from outside.getInstance()
: static method that creates or returns the existing instance.
Advantages of the Singleton
- Centralized control of instance access
- Memory saving by avoiding duplicate objects
- Useful for managing shared resources
Considerations
Although the Singleton may seem convenient, excessive use can introduce unwanted global dependencies, making the code harder to test and maintain. Use it wisely, especially in large applications.