This is me…

Singleton Pattern Class has Only One Instance and Provides a Point of Access to that Instance from any Other Object

20 min read0 comments


What?

The Singleton Pattern ensures that a class has only one instance and provides a point of access to that instance from any other object. It's often used for things like configuration managers, where you want a single source of truth accessible throughout an application.

Prerequisites:
  1. Node.js and npm installed.
  2. Basic knowledge of NestJS
  • The Singleton Pattern restricts the instantiation of a class to one single instance.
  • It is useful when you want to ensure that a class has only one instance available across the application, and you need a way to access its methods without necessarily instantiating it repeatedly.

Let's look at how to implement the Singleton Pattern in TypeScript:

First, we'll define the Singleton class:
    
class Singleton {
    // Hold the instance of the class
    private static instance: Singleton;

    // Make the constructor private so it can't be instantiated outside
    private constructor() {
        // Initialization code here
    }

    // Public method to provide access to the instance
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }

    // Example method to demonstrate
    public someMethod(): void {
        console.log('Method called on the Singleton instance');
    }
}
    
Use the Singleton:
    
const instance1 = Singleton.getInstance();
instance1.someMethod(); // Outputs: Method called on the Singleton instance

const instance2 = Singleton.getInstance();

// Demonstrates that both instances are the same
console.log(instance1 === instance2); // Outputs: true
    
Let me tell you
  • The instance property holds the Singleton instance. It's static, so it's shared across all instances of the class.
  • The constructor is private, which prevents the instantiation from outside. This ensures that the only way to get an instance of the class is via the getInstance method.
  • The getInstance method returns the Singleton instance. If no instance has been created yet, it creates one.
Benefits:
  • Ensured that a particular class is instantiated only once.
  • Provides a single point of access for that instance.
  • Lazily loaded, which means the instance isn't created until it's needed.
  • Useful for coordinating actions, managing states, or sharing resources.

However, note that in a multi-threaded environment or when dealing with multiple processes, ensuring a true Singleton can be complex and might need extra synchronization or other techniques. This is less of an issue in client-side TypeScript, but is something to be aware of in other contexts.



Next

Factory Pattern to Create Objects without Specifying the Exact Class of Object