Sunday, August 8, 2021

Singleton Design Pattern In Javascript [2021]

Must read

As the name implies, there is only one instance.

The Singleton Design Pattern is one of the creational design patterns. This is used for scenarios where only one object is needed globally, such as global caches, thread pools, window objects, etc.

Therefore only one instance in a class, even if the class is instantiated multiple times in the application, only the first instance object after the first instantiation is returned. The singleton mode reduces unnecessary memory overhead but also reduces global function and variable conflicts.

Let’s Dive into the code.

class SingletonClass {
    constructor(name){ = name
        this.instance = null
    static getInstance(name) {
        if(!this.instance) {
            this.instance = new SingletonClass(name)
        return this.instance
let John = SingletonClass.getInstance('John');
let Amy = SingletonClass.getInstance('Amy');

Console output for Object John

  instance: null,
  name: "John"

Console output for object Amy

  instance: null,
  name: "John"

Code Summary:

  • We have created SingletonClass which has two methods constructor and a static getInstance, the constructor has two properties name and instance, getInstance static methods checks if instance property is null then it will create a SingletonClass object with name-value else it will return the existing instance of the SingletonClass object
  • The first time we call the SingletonClass.getInstance(‘John’); the if condition will will be true and create a new singleton object.
  • Second time when we call the SingletonClass.getInstance(‘Amy’); the if condition will not run as the instance is already created and it will return the old singleton object.

When will the Singleton design pattern be used?

  • Singleton design pattern must be used when managing access to a resource that will be shared by your entire application globally.
  • Use a singleton pattern when a class in your application should just have a single instance example: creating a single database object shared by different parts of your application.

Advantages of Singleton design pattern

  • The object has only one instance throughout the application.
  • The object gains a global access of the instance

Learn about another design pattern Factory design pattern in JavaScript

More articles


Please enter your comment!
Please enter your name here

Latest article