The Singleton Pattern

This pattern restricts instantiation of an object to a single reference thus reducing its memory footprint and allowing a “delayed” initialization on an as-needed basis. This isn’t too common amongst JavaScript projects today but more common in WordPress (see Eric Mann’s in-depth article here).

This article is part of a series called JavaScript Design Patterns.

Advantages

Disadvantages

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
var mySingleton = ( function( window, undefined ) {
var instance = null;
// revealing module pattern that handles initialization of our new module
function initializeNewModule() {
function myMethod() {
alert( 'my method' );
}
function myOtherMethod() {
alert( 'my other method' );
}
return {
someMethod : myMethod,
someOtherMethod : myOtherMethod
};
}
// handles the prevention of additional instantiations
function getInstance() {
if( ! instance ) {
instance = new initializeNewModule();
}
return instance;
}
return {
getInstance : getInstance
};
} )( window );
 
// example usage
mySingleton.getInstance().someMethod(); // alerts "my method"
mySingleton.getInstance().someOtherMethod(); // alerts "my other method"

Additional Resources

http://robdodson.me/blog/2012/08/08/javascript-design-patterns-singleton/
http://www.dofactory.com/javascript-singleton-pattern.aspx
http://chrisiona.com/the-singleton-pattern/
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

Other Common JS Patterns

The Module Pattern
The Revealing Module Pattern
The Singleton Pattern
The Observer Pattern
The Mediator Pattern
The Prototype Pattern
The Facade Pattern
The Factory Pattern

2 responses!

Alex Kloss said: (8 months ago) Reply

The singleton pattern I remember works like this:

Singleton = new function(){
    this.method = function(args){ /* whatever */ }
    return this;
};
Jérôme Avoustin said: (7 months ago) Reply

Interesting… except that Singleton is evil !
Tight coupling and make the caller untestable.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>