JavaScript Design Patterns: Singleton

This is the first in what should be a pretty long series about JavaScript design patterns. In 1995, Erich Game, Richard Helm, Ralph Johnson and John Vlissides (known as the Gang of Four) published Design Patterns: Elements of Reusable Object-Oriented Software, a book cataloging recurring solutions to common dilemmas in software architecture and design. It also started a common vocabulary for referring to these solutions. If you’d like to know more you can find it on Wikipedia.

That book’s example implementations of each of the solutions were written in C++ and Smalltalk, which are quite different than JavaScript. Another book – Pro JavaScript Design Patterns – was written to bring many of those patterns into the context of JavaScript. My hope is to present a lot of the knowledge from that book here, but not so much that I get sued… just enough to keep you interested and possibly get you to buy the book. If you do buy the book, let them know it was because I referred you. Maybe they’ll provide me a bit of compensation (probably not, but here’s hoping).

All Alone with the Singleton

In JavaScript, the singleton is extremely simple and could possibly be excluded from the designation of singleton, but it does technically work similarly to a singleton, so it’s still useful to know. The singleton groups code into a single object so that you don’t need to instantiate a new one object whenever you need its resources, which allows you to have global access to those resources.

In JavaScript, the singleton is used mostly for namespacing and reducing the number of global variables that your application creates. This pattern is probably more useful in JavaScript than in any other language due to the high risk of using global variables in your code and the singleton’s ability to namespace those variables.

A Basic Singleton

This is the most basic and easiest to understand implementation of the singleton in JavaScript. It is simply an object literal with methods and attributes, supposedly grouped by some type of relation to one another.

var Singleton = {
	attr: 1,
	another_attr: 'value',
	
	method: function() {...},
	another_method: function() {...}
};

Since it is an object literal, it doesn’t need to be instantiated and there is then only one copy of the object. This allows access to all of the methods and attributes from a single global object, as demonstrated below:

Singleton.attr += 1;
Singleton.method();
...

JavaScript Namespacing

One of the uses of the singleton pattern in JavaScript is namespacing. With languages like Java and C#, namespacing is built into the language and is required. Creating these namespaces/packages organizes the code into logical chunks. This is a great reason to use the singleton pattern in JavaScript along with the fact that using namespaces moves your code from the global context to the new singleton, leading to fewer accidental overwrites and bugs.

Using a singleton for namespacing is quite simple. Once again you can just create an object literal:

var Namespace = {
	Util: {
		util_method1: function() {...},
		util_method2: function() {...}
	},
	Ajax: {
		ajax_method: function() {...}
	},
	some_method: function() {...}
};

As you can see, now if you want to use a utility method, then you can find it somewhere under Namespace.Util, like what is shown in the next snippet. Of course, as shown by the some_method function, the methods don’t have to be buried multiple layers into the singleton.

Namespace.Util.util_method1();
Namespace.Ajax.ajax_method();
Namespace.some_method();

Normally you might just have all of these methods as global functions, which means there is a much higher possibility that they would get overwritten, especially if it a name as simple as get, which might not be all that uncommon. You could take namespacing one step further and add all of your variables and functions to this singleton to further remove chances of your code being tampered with.

Page-Specific JavaScript Code

In many cases, some pages of a site run different JavaScript code than other pages. You can use the singleton namespacing technique to encapsulate page-specific code and have it run when the page is finished loading:

Namespace.homepage = {
	init: function() {...},
	method1: function() {...},
	method2: function() {...}
}

Namespace.contactpage = {
	init: function() {...},
	method1: function() {...},
	method2: function() {...}
}

Namespace.pageutil = {
	getPageName: function() {
		// somehow return the identifier for the current page
	}
}

var pageName = Namespace.pageutil.getPageName();
window.onload = Namespace[pageName].init;

This can be especially useful for adding code for validating different forms that appear on different pages. You can even keep functionality that is used on multiple forms in another part of the namespace, like I did with Namespace.pageutil.getPageName. This is slightly different than what I was referring to because the getPageName method isn’t really used by the page-specific code, but is actually used to find the reference to the correct page’s code.

More with Pro JavaScript Design Patterns

The book – Pro JavaScript Design Patterns – goes into much more about the singleton pattern. Other than the fact that I compressed 6 pages from the book into this comparatively small blog post, it also goes into creating private variables through the use of closures, Lazy Instantiation, and Branching. As I insinuated from the start, I don’t want to copy the book to much because I want to peek your interest enough to make you want to buy the book, which benefits us both by helping them financially while persuading them not to sue me. Not to mention that a single blog post should not encompass the same amount of material as an entire chapter in a book.

If you thought this was helpful or you just plain liked the article, please spread the word using the social sharing buttons below the post. Small town guys like me don't get big without the help of users like you. Thanks!

Stay tuned for more posts in this JavaScript Design Patterns series:

About the Author

Author: Joe Zim

Joe Zim

Joe Zimmerman has been doing web development ever since he found an HTML book on his dad's shelf when he was 12. Since then, JavaScript has grown in popularity and he has become passionate about it. He also loves to teach others though his blog and other popular blogs. When he's not writing code, he's spending time with his wife and children and leading them in God's Word.


  • http://www.facebook.com/rafaelcavalcantisilva Rafael Cavalcanti

    Top!

  • http://tedk.com.br/ Ted k’

    You always surprising with javascript, well Joe!

  • Durgesh Priyaranjan

    Too good man. I found ur blog while surfing through javascript resources on net. And I can confidently say this is one of the best resources for javascript.

    • http://www.joezimjs.com Joe Zimmerman

       Thank you very much!

  • http://www.joezimjs.com Joe Zimmerman

    1) I didn’t do a very good job of explaining when and why to use different patterns, but in the case of the singleton, you just use it whenever you want a single instance of an object that is shared throughout an app (such as a database connection on the server side).
    2) No one pattern is the best for a library. Each pattern is used for different purposes, so any one library can end up requiring the use of many patterns.
    3) The Advantages and Disadvantages are different depending on the pattern. If you read Pro JavaScript Design Patterns (you can purchase the book through the link in the 2nd paragraph of this article) it’ll show pros and cons to each pattern.
    4) Yes, many patterns are easily combined with other patterns. Very few of them can be put together in a single function, but pretty much all of them can be shared within a single JavaScript file.