start blog post

JavaScript Design Patterns: Module, Singleton

(jump to the code)

You can read about the evolution of these patterns at KlausKomenda, along with an example that solves the same task using a number of different patterns so you can see the progression. The patterns described here are the Module and the Singleton.

The Module (more specifically, the Revealing Module) is a design pattern that provides encapsulation for data members and/or functions. Why do we care? Here are some benefits:

  • Encapsulation avoids naming conflicts with other code on the page.
  • Encapsulated data can only be accessed via public methods (if provided), which lets the module perform any necessary validation before changing data. This is not "hack proof", nor does it intend to be. It simply means that private data is scoped to the module itself, and does not exist in the "public" world. See the following code for examples.
  • Encourages coding behavior that produces high cohesion and loose coupling.
  • Improves code readibility and reuse. You can often copy well-written modules to other projects without changing a line of code.
    var RevealingModule = function() {
        
        // private variables and functions go here
        var myPrivateVar = 'test';
        function getVar() {
            return myPrivateVar;
        }
        function setVar(newVar) {
            myPrivateVar = newVar;
        }

        return {
            // public methods are revealed here
            getVar: getVar,
            setVar: setVar
        };
         
    };
    
    // each instance gets its own copies of private data
    var modFirst = new RevealingModule();
    var modSecond = new RevealingModule();
    
    // changing one instance does not affect other instances
    modSecond.setVar('new value');
    alert(modSecond.getVar()); // 'new value'
    alert(modFirst.getVar());  // 'test'

A Singleton is an object that only has one instance. The easy way to accomplish this in JavaScript is to start with the Module pattern, then immediately instantiate it by using inline execution.

    // Dude looks like a Module...
    var Dude = function() {
        // private members and functions
        var name = "";
        var age = 0;
        function modifyAge(years) {
            age = age + years;
        }
        
        // these methods will be revealed below
        function getAge() { return age; }
        function getName() { return name; }
        function setAge(newAge) { age = newAge; }
        function setName(newName) { name = newName; }
        
        return {
            getName: getName,
            setName: setName,
            getAge: getAge,
            setAge: setAge,
            
            // public names do NOT have to match private names
            changeName: setName,
            
            // you can also return additional public methods
            haveBirthday: function() {
                modifyAge(1);
                alert(name + ' is now ' + age + ' years old!');
            },
            sayHello: function() {
                // other public methods can be called using "this"
                alert(this.getName() + ' says hello!');
            }
        }
        
    }(); // inline execution turns this Module into a Singleton
    
    // cannot instantiate Dudes, there can be only one
    var myDude = new Dude(); // TypeError: Dude is not a constructor
    
    /*
     * We can't make a new instance using "var myDude = new Dude();"
     * because Dude is an Object, not a Function. Instead, access 
     * Dude's public functions directly, like this:
     */
    Dude.setName('John');
    Dude.setAge(36);
    Dude.haveBirthday(); // alerts 'John is now 37 years old!'
    
    // private data will not be overwritten, it is bound immediately at creation
    Dude.name = 'Jim';     // this makes a new, PUBLIC property called "name"
    alert(Dude.getName()); // 'John' (public method accessing private property)
    alert(Dude.name);      // 'Jim' (public property we just created)
    alert(Dude.age);       // 'undefined' (only exists in private scope)

Modules and Singletons can be great for code reuse, because they can provide a simple public interface which doesn't have to change when its inner workings change. Some Singleton examples:

var tags = [, ];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

8 Comments

avatarRicardo

The module pattern can also be written this way:


var Module = function() {

// private variables and functions go here
var myPrivateVar = 'test';

this.getVar = function() {
return myPrivateVar;
}
this.setVar = function(newVar) {
myPrivateVar = newVar;
};
};


You don't need to return an object (unless there is some advantage I don't see). In this example you lose function names in a stack trace, but it's easy to keep named functions and just do an assignment if needed.

avatarHB

You're right, but that much is a matter of preference. Really, in both cases the pattern "returns an object", just one is more explicit. When your example Module is instantiated, you get an object with those methods set, just like the revealing module pattern in the post.

Another (perhaps small) benefit is it's easy to change the public interface if it's all revealed at the end of the module. You can comment out a single line to avoid revealing that method, but it's a little more complicated if defined using this.fn = function() {...};.

Thanks very much for posting that example, and you also happened to stumble across a formatting bug in my blog code! All fixed now.

avatarmiguel

Thank you for simple explanation of these patterns

avatarHB

You're welcome! I'm glad it helped, and thanks for taking the time to comment.

avatarAndrea Giammarchi


function Singleton(){};
// whatever prototype ...
Singleton.getInstance = (function(instance){
return function getInstance(){return instance};
})(new Singleton);

Above is just one example of a more simple Singleton, integrated with normal behavior and a unique shared instance. JavaScript is flexible, common OOP patterns can be easily transformed in something more usable, fun, portable, flexible, etc ... if you want a more classic implementation with lazy instance declaration:


var Singleton = (function(instance){
return function Singleton(){
return instance || (instance =
this instanceof Singleton ? this : new Singleton
);
};
})();

alert(Singleton() === new Singleton);
// true

avatarAndrea Giammarchi

well, you can read I closed and reopen the tag, make your parser a bit less greedy via question mark "?" before the closed tag :-)

avatarHB

Figured, that was the one tag that I missed an ungreedy on. Thanks for finding it for me =)

That first example is a Singleton only if everyone who uses it plays nicely and uses getInstance(). But it doesn't stop people from actually creating new Singleton() instances that are not identical to each other.

The second example definitely does catch that, though, good idea. Thanks for posting!

avatarKrishna Chaitanya T

Thank you so much for the info. Infact, I got my concepts consolidated after reading your article. I've used your link as reference in my article Love JavaScript design patterns, love your jQuery code even more!