JavaScript: The Singleton Pattern

The singleton pattern is the most commonly used design pattern and one that you will probably is more than any others. It provides a great way to wrap code into logical unit that can be accessed through a single variable.

The Singleton design pattern is used when only one instance of object is needed throughout the lifetime of an application.  

In JavaScript there is different way to achieve singleton object than any other object oriented supported language (Java, C++). In JavaScript Singleton pattern have many uses, they can be used for Namespace, which reduce the number of global variables in your page (Prevent from polluting global space), Organizing code in a consistent manner, which increase the readability and maintainability of your pages.

There are two important point in the traditional definition of Singleton pattern

  • There should be only one instance allowed for a class and
  • We should allow global point of access to that single instance

Let me define singleton pattern in JavaScript context:

“It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to instantiate than it can be instantiate only once.”

In JavaScript we can create singleton though object literal, However there are some another way but that I will cover in next post.

A singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is key feature of the singleton pattern.

JavaScript: A Singleton as a Namespace

As I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it.

A common example which happen frequently when you are working with another team member parallel,

/* Declare globally */

function findUserName(id){
    
}

/* Later in the page another programmer 
added code */
var findUserName = $('#user_list');

/* You are trying to call 😦 */
console.log(findUserName())

One of the best way to prevent accidentally overwriting variable is to namespace your code within a singleton object.

/*  Using Namespace */

var MyNameSpace = {
    
    findUserName : function(id){
        
    },
    // Other methods and attribute go here as well 
}

/* Later in the page another programmer 
added code */
var findUserName = $('#user_list');

/* You are trying to call and you make this time workable */
console.log(MyNameSpace.findUserName());

UML Diagram for Singleton design pattern:

CaptureUML diagram for the same is given below. This implementation provide global access to the object through static method getInstance().

Singleton Design Pattern Implementation

/* Lazy Instantiation skeleton for a singleton pattern */

var MyNameSpace = {};
MyNameSpace.Singleton = (function(){

  // Private attribute that holds the single instance
  var singletonInstance;  
    
      // All of the normal code goes here 
      function constructor(){
          // Private members
          var privateVar1 = "Nishant";
          var privateVar2 = [1,2,3,4,5];
          
          function privateMethod1(){
              // code stuff
          }
          
          function privateMethod1(){
              // code stuff
          }
          
          return {
              attribute1 : "Nishant",
              publicMethod: function(){
                  alert("Nishant");// some code logic
              }
          }
      }
      
      return {
        // public method ( Global access point to Singleton object) 
        getInstance: function(){
            //instance already exist then return  
           if(!singletonInstance){
                singletonInstance = constructor();
           }
           return singletonInstance;           
        }           
      }
  }
})();   

// getting access of publicMethod 
console.log(MyNamespace.Singleton.getInstance().publicMethod());

The singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.

Advertisements