Typescript - Singleton pattern Implementation with example

In this blog post, We are going to learn the Singleton pattern in typescript with examples.

Singleton Design pattern 

Singleton is one of the simple and frequently used design patterns in application development. This pattern enables to create a single instance or object of a class in the application. Only Once an instance of the class is created in an application.
Every programming language provides an implementation for this pattern.
We can also implement the singleton pattern in Typescript. This is a simple creation pattern.

Use cases and advantages 

  1. Providing global access for object creation of a class, It always has one instance is maintained.
  2. In applications, If you are implementing application caching, You will maintain an only single instance of a cache object always.
  3. Maintain single instance when you are dealing with the global configuration in the application

Singleton Pattern implementation

  1. Private modifier for the constructor, So that This class cannot be created by other classes.
  2. A private Static variable that always returns the instance of the same class 
  3. A public static function that returns the instance of the class


class SingletonClass {  
    private static instance: SingletonClass;  
    private constructor() {  
    static getInstance() {  
        if (!SingletonClass.instance) {  
            SingletonClass.instance = new SingletonClass();  
        return SingletonClass.instance;  
let instance1 = new SingletonClass() // This gives compilation error  
let instance2 = SingletonClass.getInstance()   
let instance3 = SingletonClass.getInstance()   
console.log(instance2==instance3) // true  

If you create an object using the new operator, it gives compilation error - constructor of class ‘SingletonClass’ is private only accessible within class declaration Created Instance static member variables, which can be accessed using class instead of Object instances added private modifier to Constructor, Outside classes can not be created using the new operator. Declared static method or a function, which checks if the instance is null or undefined, it creates an instance and returns it, if already exist, just returned the instance

Similar Posts