Coding Guru

Code never does the mistake, we make the mistakes in the code. Think, Imagine, Phrase and then Code.

The Singleton Pattern

As the name suggests the pattern belongs to the methodology where a single instance is being created for an object thus it reduce the memory usage and the initialization of an instance on dynamic or when required basis. It enables a developer to create a class whose functionality has to remain constant for multiple instances like Ajax or Util class.

If we talk in the terms of software engineering, this can be done by creating a class with the function which creates an instance for a class only if it doesn't exist otherwise returns the same object. In terms of javascript development the singleton class acts as a namespace which provides only one point of access for the methods and variables. 

Diagram


In JavaScript a singleton can take multiple forms but the simplest is where an object literal is being grouped together which all the related methods and variables or properties as follows:

var singletonPattern =  {
myProperty : "Its me",
otherProperty : "Its not me",
myFunction : function(){
console.log('Hey.......');
}};
Simple! Yes the approach is quiet simple but it enforce the functions to be public only. To make the singleton object better its required to create a class and then exposing the method into the class which return the same object all the times. And to do this , the exposed method must check the existance of the object every time and returning the same object else the new one. Lets have an example:

var Car = (function(){
              var carInstance; //private variable to hold the
                               //only instance of Car that will exits.
 
              var createCar = function(){
                         var privateModel = Skoda-Fabia; //private
                         var changeModel = function(model){
                             privateModel = model;  
                         }
                         var publicSwitch = function(model){                                 
                                  changeModel(model);
                         };
                         var getModel = function(){
                                  return privateModel;
                         };
                         return {
                                publicSwitch : publicSwitch ,
                                getModel : getModel  
                        };
              };
 
              return {
                    getInstance: function(){
                          if(!carInstance){
                              carInstance = createCar();
                          }
                          return carInstance;
                    }
              };
})();

Lets have a close eye on the above stub. Now we have created a variable Car , and instantiated it by using JavaScript Revealing Module Pattern. and instead of exposing the declared members, we have returned a property as getInstance() as below:
 return {
                    getInstance: function(){
                          if(!carInstance){
                              carInstance = createCar();
                          }
                          return carInstance;
                    }
              };

In this section the Car variable is initialized with the return statement. Hence whenever this instance will be required in our code , we will use the code as :
var myCar = Car.getInstance();

And the getInstance function first checks if already the instance of "carInstance" exist then the same is retured otherwise a new one as described in above sections also.
Now lets have a look how the createCar() works:
 var createCar = function(){
                         var privateModel = Skoda-Fabia; //private
                         var changeModel = function(model){
                             privateModel = model;  
                         }
                         var publicSwitch = function(model){                                 
                                  changeModel(model);
                         };
                         var getModel = function(){
                                  return privateModel;
                         };
                         return {
                                publicSwitch : publicSwitch ,
                                getModel : getModel  
                        };
              };

In this function the private and public properties are implemented. This function returns the object with two properties 'publicSwitch' and 'getModel'. It also contains the private methods but are not exposed but will always work there in the closure. Calling createCar() will always create and return the new object of with property 'publicSwitch'. So its required to be ensure that the createCar() is being called just once and the instance obtained from it is being stored into a variable and returned on any further request for the same  function. This instance is saved into private variable 'carInstance' and any call to 'getInstance' will first check whether the carInstance already exists or not.

Wanna test the code ! Lets do it then:

var carA = Car.getInstance();
var carB = Car.getInstance();
console.log(carA === carB); //true
carB.publicSwitch('VolksVagon-Polo'); //Change the model for car b
var modelCarA = carA.getModel();
var modelCarB = carB.getModel();
console.log(modelCarA === modelCarB); //true

It looks like the Module Pattern is also a type of Singleton pattern however it does not expose the getInstance() Method which we consider the signature of a Singleton pattern.

Pingbacks and trackbacks (1)+

Loading