Skip navigation

Tag Archives: Singleton Pattern


In the previous post (JavaScript Singleton pattern), we saw the basic structure of JavaScript Singleton pattern. Then what is the need of JavaScript Lazy loading Singleton pattern? You can understand that JavaScript Singleton pattern which explain in previous post becomes performance issue if the code inside singleton object becomes more and more because the ananimous function executes immediately and returns properties, function, etc into singleton object immediately when .js files loads.

So it is wise to execute the function when it requires really. For that we need to define getInstance() method which checks to see whether the singleton has been instantiated. If not, it will instantiated and returned.  If it has, a stored copy is returned.

NameSpace.Singleton = (function(){
	var instance;
	function constructor() { // normal singlton goes here
		// Private members
		var privateAttr1 = false;
		var privateAtrr2 = [1,2,3];
		function privateMethod1(){
			// code goes here
		}
		function privateMethod2(){args
			// code goes here
		}
		return {  // Public members
			publicAttr1 : true;
			publicAttr2 : 25,
			publicMethod1 : function() {
				// code goes here
			},
			publicMethod2 : function(args) {
				// code goes here
			}
		};
	}
	return {
		getInstance : function(){
			if(!instance) {  // check already exists
				instance = constructor();
			}
			return instance;
		}
	}
})();

// Here is how the public function get called.
NameSpace.Singleton.getInstance().publicMethod1();

Planning to post few JavaScript pattern as series. Here goes the first basic javscript pattern: Singleton pattern. First let us see the generalised code for this pattern.

NameSpace.Singleton = (function(){

	// Private members
	var privateAttr1 = false;
	var privateAtrr2 = [1,2,3];
	function privateMethod1(){
		// code goes here
	}
	function privateMethod2(){args
		// code goes here
	}
	return {  // Public members
		publicAttr1 : true;
		publicAttr2 : 25,
		publicMethod1 : function() {
			// code goes here
		},
		publicMethod2 : function(args) {
			// code goes here
		}
	};
})();

What are the advantages of this pattern?

  • Namespacing
  • Grouping related methods and attributes together.

What are the drawbacks of this pattern?

  • Tightly coupled
  • Unit testing is difficult

For private variable in Javascript read my previous post http://vkanakaraj.wordpress.com/2009/05/07/public-privileged-static-members/

Follow

Get every new post delivered to your Inbox.

Join 150 other followers