Open In App

How to define Singleton in TypeScript?

In this article, we will learn about the Singleton in TypeScript. A singleton is a class that always has only one instance of it at the global level. If more than one instance is created then they all will refer to the same instance and changes in the properties of one instance will reflect in the properties of all the instances.

Let us now see how we can create a singleton in TypeScript.



Approach

Example 1: The below example will show you how you can create a simple singleton in TypeScript.




class DemoSingleton {
    private static myInstance:
        DemoSingleton | null = null;
    private constructor() {
    }
 
    static getSingletonInstance():
        DemoSingleton {
        if (!DemoSingleton.myInstance) {
            DemoSingleton.myInstance =
                new DemoSingleton();
        }
        return DemoSingleton.myInstance;
    }
}
 
// It will create a new instance of
// singleton and assign it to instance1
const instance1 = DemoSingleton.
    getSingletonInstance();
 
// It assigns the already created
// instance to instance2
const instance2 = DemoSingleton.
    getSingletonInstance();
 
 
// true, both instances refer
// to the same object
console.log(instance1 === instance2);

Output:



true

Example 2: The below example explains how the properties can be changed for multiple instances that refers to the same object.




class DemoSingleton {
    private static myInstance:
        DemoSingleton | null = null;
 
    public name: string = "";
 
    private constructor() {
    }
 
    static getSingletonInstance():
        DemoSingleton {
        if (!DemoSingleton.myInstance) {
            DemoSingleton.myInstance = new DemoSingleton();
        }
        return DemoSingleton.myInstance;
    }
 
    public printMessage(name: string): void {
        this.name = name;
        console.log(`Name: ${name}`);
    }
}
 
// It will create a new instance of
// singleton and assign it to instance1
const instance1 = DemoSingleton.
    getSingletonInstance();
 
// It assigns the already created
// instance to instance2
const instance2 = DemoSingleton.
    getSingletonInstance();
 
// Here instance1 and instance2 both
// refers to the same object
 
// It assigns the same value to name
// property of both instances
instance1.name = "GeeksforGeeks";
console.log(instance1.name, instance2.name);
 
// It updates the name property of
// both the instances
instance2.name = "Google";
console.log(instance1.name, instance2.name);
 
// true, both instances refer to the same object
console.log(instance1.name === instance2.name);

Output:

GeeksforGeeks,  GeeksforGeeks
Google, Google
true

Article Tags :