In TypeScript, you can implement the Singleton pattern using a class and a static instance property. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Here's an example of how you can implement a Singleton pattern in TypeScript:
typescriptclass Singleton {
private static instance: Singleton;
private constructor() {
// Private constructor to prevent instantiation
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someMethod(): void {
console.log("Some method of the Singleton class");
}
}
// Example usage
const instance1 = Singleton.getInstance();
instance1.someMethod();
const instance2 = Singleton.getInstance();
// Both instances point to the same object
console.log(instance1 === instance2); // Output: true
In this example:
The instance
property is declared as private and static, ensuring that it is only accessible within the class and is shared among all instances.
The constructor
is marked as private to prevent external instantiation of the class.
The getInstance
method is used to get the instance of the Singleton class. If an instance doesn't exist, it creates one; otherwise, it returns the existing instance.
When you create multiple instances using Singleton.getInstance()
, they will all refer to the same instance of the class.
By using this pattern, you ensure that there is only one instance of the class, and you can access it globally through the getInstance
method.