TypeScript Singleton Pattern Example

This post shows how to use the Singleton Pattern in TypeScript with an example.
Singleton is a creational design pattern, which ensures a class has only one instance and provides a global point of access to it.

Singleton Pattern Structure

Singleton Pattern Example

Let's create a file named "Singleton.ts", add the following code to it.
/**
 * The Singleton class defines the `getInstance` method that lets clients access
 * the unique singleton instance.
 */
class Singleton {
    
    private static instance: Singleton;

    /**
     * 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(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }

        return Singleton.instance;
    }

    /**
     *  addition of two numbers
     */
    public addition(first: number, second: number) {
        return first + second;
    }

    /**
     * substraction of two numbers
     */
    public substraction(first: number, second: number) {
        return first - second;
    }

    /**
     * multiplication of two numbers
     */
    public multiplication(first: number, second: number) {
        return first * second;
    }
}

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

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

    console.log(s1.addition(10,20));
    console.log(s2.substraction(20,10));
    console.log(s1.multiplication(10, 20));
}

clientCode();
The key points are:
  • constructor with a private access modifier, so that it isn’t accessible outside of the class body,
  • static instance filed which is supposed to reference the single instance of the class,
  • static getInstance method which is responsible for returning the instance of the class. In addition, it follows a lazy evaluation strategy, hence it has to create the instance when it’s called for the first time.
Run:
  1. Compile the above code using the TypeScript compiler.
  2. Above code is compiled to plan JavaScript code
  3. Run Javascript code using node
C:\typescript-design-patterns\singleton> tsc .\Singleton.ts
C:\typescript-design-patterns\singleton> node .\Singleton.js
Output:
Singleton works, both variables contain the same instance.
30
10
200
The above "Singleton.ts" file compiled into below plan JavaScript code by TypeScript compiler:
/**
 * The Singleton class defines the `getInstance` method that lets clients access
 * the unique singleton instance.
 */
var Singleton = /** @class */ (function () {
    /**
     * The Singleton's constructor should always be private to prevent direct
     * construction calls with the `new` operator.
     */
    function Singleton() {
    }
    /**
     * 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.
     */
    Singleton.getInstance = function () {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    };
    /**
     *  addition of two numbers
     */
    Singleton.prototype.addition = function (first, second) {
        return first + second;
    };
    /**
     * substraction of two numbers
     */
    Singleton.prototype.substraction = function (first, second) {
        return first - second;
    };
    /**
     * multiplication of two numbers
     */
    Singleton.prototype.multiplication = function (first, second) {
        return first * second;
    };
    return Singleton;
}());
/**
 * The client code.
 */
function clientCode() {
    var s1 = Singleton.getInstance();
    var s2 = Singleton.getInstance();
    if (s1 === s2) {
        console.log('Singleton works, both variables contain the same instance.');
    }
    else {
        console.log('Singleton failed, variables contain different instances.');
    }
    console.log(s1.addition(10, 20));
    console.log(s2.substraction(20, 10));
    console.log(s1.multiplication(10, 20));
}
clientCode();

Comments