Design Patterns in Javascript Part 4

Posted By : Rudhishthir Prakash | 23-Sep-2018
The Singleton Pattern:
 
It is easy to assume that a module is a singleton and a singleton is a module but that isn't the case because they have two distinct purposes. The purpose of the module is to cleanly separate units of code but that is completely different from a singleton.
The intent of the Singleton is to ensure a class only has one instance and provide a global point of access to it and of course, this is JavaScript, and we don't have classes.
So, to rephrase this for Javascript, ensure an object only has one instance and provide a global point of access to it. So, when we talk about Singleton, we are not talking about the single instance of an object, we're talking about the thing that ensures that there is only one instance of the object and provides access to that one instance.
 
For example:
var dom = (function(){
	var _counter = 0;
	var instance;
	
	function generateId(){
		return "customId" + _counter++;
	}
	function create(tagName, id){
		var el = document.createElement(tagName);
		el.id = id || generateId();
		return el;		
	}	
	function createInstance(){
		return{
			generateId: generateId,
			create: create
		};
	}	
	return{
		getInstance: function(){
			return instance || (instance = createInstance());
		}
	};
}());
So, no matter how many times we call this instance method, we get the same object from this method.
 
The Singleton Pattern does have its uses but as far as Javascript is concerned, if you find yourself needing the singleton, then you need to re-evaluate your code. It could indicate that the modules in your application are tightly coupled plus Singleton can be more difficult to test and of course, this does not mean that you have to avoid the Singleton at all costs. They are useful, but just be careful when you use them.
Use Case:
They represent an interface of something where it wouldn’t make any sense to have more than one or cannot have more than one display managers or global observable's.
Example:
It is a commonly occurring pattern and there are multiple ways to implement it in JavaScript. One can use a command pattern to decouple the parsing of byte stream when implementing a protocol from the action associated to the message.

About Author

Author Image
Rudhishthir Prakash

Rudhishthir is a technical enthusiast having experience in C#.NET, NodeJS & various front-end technologies. He has great experience in building quality applications with innovative ideas. He also has proven expertise in handling clients.

Request for Proposal

Name is required

Comment is required

Sending message..