JS(Javascript) Design Pattern : Basics 1
Design Pattern Part 1 By Vinod Chauhan

JS(Javascript) Design Pattern : Basics 1

Hello Everyone, Today I am going to explain you different design pattern which we use either knowingly or unknowingly in Javascript. These pattern are very much crucial and prominent if you want to learn js or preparing for any interview. So let's get started.

SINGLETON : This design pattern is used only when we want to ensure that a class have a single instance throughout the application and has global access to it.

Above design patterns are important and required in many applications. For example : Think of an e-commerce website where we need a shopping-cart class. We need it only one and single class object for single user.

Singleton Class can be implemented by using three practices :

  1. Singleton with private variables - Using closures
  2. Singleton - Using property of constructor
  3. Singleton - Using Global Variable

Singleton Using Closures :

For easy understanding, Think of creation of Humans by GOD. There are multiple religions and multiple gods as per understanding of humans which running our universe. But even with huge number of amenities for creation and destruction of the living beings there may be a single counter for counting living species and if someone take birth or got dead this counter will be updated by all the so-called different GODS to make it consistent. Let's take an example of it.

var GOD = (function(){
              var myInstance; // Private variable to maintain single instance.
              var createGOD = function(){
                         var totalLives = 700000000;
                         var NewLifeCreated = function(){
                             totalLives++;   
                         }
                         var reduceALife = function(){
                                  totalLives--;
                         };
                         var getLifeCount = function(){
                                  return totalLives;
                         };
                         return {
                                birth: NewLifeCreated,
                                death: reduceALife,
                                population: getLifeCount
                         };
              };
              return {
                    getInstance: function(){
                          if(!myInstance){
                              myInstance = createGOD(); 
                          }
                          return myInstance; 
                    }
              };
})();


// Let's try to create multiple Gods now.


var religion_1_God = God.getInstance();
var religion_2_God = God.getInstance();


console.log("People created by God of religion 1: " + religion_1_God.population())
console.log("People created by God of religion 2: " + religion_2_God.population())


console.log("A child is born in religion 1.")
religion_1_God.birth();
console.log("People created by God of religion 1: " + religion_1_God.population())
console.log("People created by God of religion 2: " + religion_2_God.population())


console.log("A person died in religion 2.")
religion_2_God.death();


console.log("People created by God of religion 1: " + religion_1_God.population())
console.log("People created by God of religion 2: " + religion_2_God.population())


trace("Oh.. God is one.")

Using Property of Constructor :

// Create a class
function MyClass(){
  if(typeof MyClass.MyInstance === "undefined"){
    console.log("Will execute this only once.")
    MyClass.MyInstance = this;
  }
  return MyClass.MyInstance;
}


// Try to create two objects of MyClass
var obj1 = new MyClass();
obj1.name = "Vinod";


console.log("Name of first object is: "+ obj1.name)


var obj2 = new MyClass();
console.log("Name of second object is: "+ obj2.name)


console.log("Name of MyClass.MyInstance is: "+ MyClass.MyInstance.name);

Using Global Instance :

This one is same as above with minimal changes. If you guys are interested then you can try first otherwise you can ask me directly to give you one example of it.


ITERATOR

This pattern is used when we want to iterator or loop over the collection of objects. It simply means, When an Object stores other objects then in some conditions we want to iterate over it without understanding of it internal structure. This pattern provides a 'next()' method which gives the next set of objects stored in it.

var itrObj = (function() {
  var index = 0,
        data = ["a", "b", "c", 4, 5],
        length = data.length;

        return {
            next: function() {
                var element;
                if (this.hasNext()) {
                    element = data[index];
                    index = index + 1;
                    return element;
                }
                return null;
            },
            hasNext: function() {
                return index < length;
            }
        }
} )()
console.log(itrObj.next()); // a
console.log(itrObj.next()); // b
console.log(itrObj.next()); // c
console.log(itrObj.next()); // 4
console.log(itrObj.next()); // 5
console.log(itrObj.next()); // null

DECORATOR

This pattern provides an additional functionality to add features in an existing object.

I will give example of this design pattern in next part with some additional Patterns. Till then you can try it with your own interest and let me know how this article is.


To be Continued....

Precise and informative. Thanks

Like
Reply

To view or add a comment, sign in

More articles by Vinod Chauhan

Others also viewed

Explore content categories