Friday, April 16, 2021

Typescript: Singleton

 Singleton is a design pattern that ensures that only one objects exits.

/**
 * The Singleton class defines the `getInstance` method that lets clients access
 * the unique singleton instance.
 */
 class ExampleSingleton {
    private static instanceExampleSingleton;

    /**
     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
     */
    private constructor() { }

    /**
     * The static method that controls the access to the singleton instance.
     *
     * This implementation let you subclass the Singleton class while keeping
     * just one instance of each subclass around.
     */
    public static getInstance(): ExampleSingleton {
        if (!ExampleSingleton.instance) {
            ExampleSingleton.instance = new ExampleSingleton();
        }

        return ExampleSingleton.instance;
    }

    /**
     * Finally, any singleton should define some business logic, which can be
     * executed on its instance.
     */
    public someBusinessLogic() {
        // ...
    }
}

/**
 * The client code.
 */
function clientCode() {
    const s1 = ExampleSingleton.getInstance();
    const s2 = ExampleSingleton.getInstance();

    if (s1 === s2) {
        console.log('Singleton works, both variables contain the same instance.');
    } else {
        console.log('Singleton failed, variables contain different instances.');
    }
}

clientCode();

Singleton used case can be logging class where we can re-use the object.

No comments:

Post a Comment