How to implement a singleton pattern in TypeScript



Image not found!!

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:

typescript
class 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:

  1. The instance property is declared as private and static, ensuring that it is only accessible within the class and is shared among all instances.

  2. The constructor is marked as private to prevent external instantiation of the class.

  3. 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.

  4. 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.