Friday, 10 May 2013

JavaScript - Singleton pattern

In the world of object oriented programming languages, singleton pattern is very significant. It is all about making sure that only one instance of the object is created in its life time. It can be easily achieved in JavaScript as there are no true classes present unlike Java or C++. 


 var Singleton = (function(){  
      var instance;  
      createInstance = function(){  
           console.log("Creating instance...");  
           var attribute1 = "Hello";  
           var attribute2 = "How are you";            
           return {  
                getAttribute : function(param){  
                     if(!param) {  
                          console.log("No parameter specified. Exiting...");  
                          return false;  
                     if(param === 1){  
                          console.log("Value is >>> "+attribute1);  
                     } else {  
                          console.log("Value is >>> "+attribute2);  
      return {  
           getInstance : function(){  
                     instance = createInstance();  
                return instance;  
 function check(){  
      var instance1 = Singleton.getInstance();  
      var instance2 = Singleton.getInstance();  
 <button onclick="check()">Check</button>  

After clicking on Check button, take a look at the console. You can see that createInstance method is invoked only once. 

There are a couple of things to notice here. Inside getInstance method, createInstance is invoked only if instance is undefined. Another key point is it is a self executable function and you can not make a call as follows.
var instance3 = new Singleton(); //error
var instance4 = new Singleton().getInstance();// error 

So the only access point to instance is Singleton.getIntance(). 

A design pattern is evolved out of programming experience. Though Singleton pattern is very popular and it has certain rules to follow, you can associate your own features to this pattern as you wish by not losing the basics.

Have a nice day! 

1 comment:

  1. Singleton is way easy in JS

    var TheOne = {doSomething: function(){}, ONE: 1}

    this is singleton. ^^^