Tuesday 18 February 2020

Singleton Design Pattern in JavaScript

Singleton Design Patterns in JavaScript
  • Singleton Design Pattern we use when we want only Single instance of a class.
  • It restricts the instantiation of class to one Object.
  • It is useful for the applications that operate more efficiently when only one object exists, or restrict the instantiation to a certain number of objects.
Lets see it in examples:
let obj = (function() {

  // Private Variable
  let objInstance;

  // Private Function to create methods and properties
  function employee() {

    let empName, empAge;

    let addEmployeeName = function() {
      empName = "Elon";
    }

    let addEmployeeAge = function() {
      empAge = 30;
    }

    let getEmployeeInfo = function() {
      return `My name is ${empName} and I'm ${empAge} years old`;
    }

    return {
      addEmployeeName: addEmployeeName,
      addEmployeeAge: addEmployeeAge,
      getEmployeeInfo: getEmployeeInfo
    }
  }

  return {
    getInstance: function() {
      // If objInstance doesnt exist call employee method
      if (!objInstance) {
        // Call employee method and assign to objInstance
        objInstance = employee();
      }

      // If objInstance exists return it as it is
      return objInstance;
    }
  }

})();

// Now create one instance
let obj1 = obj.getInstance();
obj1.addEmployeeName();
obj1.addEmployeeAge();

// Create one more instance
let obj2 = obj.getInstance();
obj2.addEmployeeName();
obj2.addEmployeeAge();

// Compare both objects
console.log(obj1 === obj2);

// This will return true becauase 

Here, we have created the obj which is an IIFE (Immediately Invoked Function Expression) and from it we are returning getInstance function. getInstance checks whether the instance has already created or not by checking objInstance variable.

If objInstance does not exists then it will call the employee function which returns an object containing addEmployeeAge, addEmployeeName and getEmployeeInfo methods and assigns it to objInstance variable.

employee() function will get called only first time when we instantiate object. Next time it will return the same object.

3 comments:

  1. Easy "water hack" burns 2 lbs OVERNIGHT

    More than 160 000 men and women are hacking their diet with a easy and secret "liquids hack" to lose 1-2lbs every night as they sleep.

    It's proven and it works with anybody.

    Just follow these easy step:

    1) Grab a drinking glass and fill it with water half full

    2) And then do this amazing hack

    and become 1-2lbs lighter the next day!

    ReplyDelete