TypeScript Singleton Pattern Example

1. Definition

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It involves a single class which is responsible for creating its own object while making sure that only a single object gets created.

2. Problem Statement

Imagine a situation where you want to ensure that only one instance of a particular class is ever created during the lifetime of your application, perhaps because it manages a shared resource like a configuration object or a connection pool. Instantiating multiple instances could lead to undesired behavior, inconsistencies or resource conflicts.

3. Solution

The Singleton pattern restricts the instantiation of a class to one single instance and provides a method to retrieve this instance.

4. Real-World Use Cases

1. Database connection pools where you want to avoid the overhead of establishing a connection every time one is required.

2. Configuration management where multiple parts of an application need to access a shared configuration object.

3. Logger classes where messages from various parts of an application should go to a single log file or display.

5. Implementation Steps

1. Declare the class constructor as private to prevent external instantiation.

2. Create a private static variable to hold the singleton instance.

3. Provide a public static method to get the instance of the class.

6. Implementation in TypeScript

class Singleton {
    // 1. Create a private static variable to hold the singleton instance.
    private static instance: Singleton;
    // 1. Declare the class constructor as private to prevent external instantiation.
    private constructor() {
        // Initialization code here
    }
    // 3. Provide a public static method to get the instance of the class.
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }
}
// Usage:
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);  // Outputs: true

Output:

true

Explanation:

In the above TypeScript implementation, the Singleton class has a private constructor to prevent external code from creating new instances. 

The getInstance method checks if an instance of the class already exists. If not, it creates one and then returns it. Any subsequent calls to getInstance will always return the same instance, thereby ensuring that only one instance of the class exists in the application. The output 'true' confirms that the two variables instance1 and instance2 point to the same object in memory.

7. When to use?

The Singleton pattern is applicable when:

1. There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.

2. The sole instance should be extendable by subclassing, and clients should be able to use an extended instance without modifying their code.


Comments