Showing posts with label singleton design pattern. Show all posts
Showing posts with label singleton design pattern. Show all posts

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.