Design pattern: Singleton (TypeScript examples)
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.
Here’s an example of implementing the Singleton pattern in TypeScript:
class Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor to prevent direct instantiation
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod(): void {
console.log("Singleton method called");
}
}
// Usage:
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // Output: true
instance1.someMethod(); // Output: "Singleton method called"
In this example, the Singleton
class has a private constructor to prevent direct instantiation. The getInstance
method provides a way to access the singleton instance. When called for the first time, it creates a new instance of Singleton
. On subsequent calls, it returns the existing instance.
When you run the code, you’ll see that instance1
and instance2
refer to the same object, indicating that only one instance of the Singleton class exists.