Design patterns in Javascript : Singleton

 

The singleton patterns was documented as a solution to a simple problem, “Only one object of class X can be instantiated at any time in the application”

Typically a singleton is implemented by restricting access to the class constructor, effectively making impossible to instantiate the class

It is common to use singletons for application wide configuration or database access classes.

If you worked with ExtJS framework before you most likely have used a singleton often, the Ext singleton is the framework entry point, and only one instance of that object is ever executed during the live cycle of the application

Singletons are completely supported in JavaScript without any further coding, meaning they are part of the language, although they are not as useful as they could, as there is no support of private variables or members.

var singleton = {
    value : 500
};
 
var ex1 = singleton;
var ex2 = singleton;
ex2.value = 100;
 
console.log (ex1.value); //output 100

As you can see the lack of support for private members narrows the potential uses.

Fortunately the classical singleton implementation can easily be achieved in JavaScript

var singleton = function(options){
    //private methods and variables
    function singletonInstance(options){
        this.options = options || {};
    };
    var myInstance;
    return {
        //public methods and variables
        getInstance : function(options){
            if(myInstance == undefined){
                myInstance = new singletonInstance(options);
            }
            return myInstance;
        }
    }
}();
 
var ex1 = singleton.getInstance({value: 100});
var ex2 = singleton.getInstance();
ex2.options.value = 200;
 
console.log(ex1.options.value);//outputs 200

 

As you can see this is a more complex solution but the advantage is that we can have public and private members.

In our situation, as we pretend to extend Ext, or more precisely we are creating code intended to be used by other code, not exposing our internal logic is very useful as we only need to worry about backwards compatibility for our public interface and not for our internal code

This code introduces some key factors:

Auto executing functions

Private and public variables

The singleton is created using an auto executing function or object.

To create an auto executing function or object the trick is to add () to the end of its declarations, like this:

Function foo(){
    //some code
}()

Private and public members are also easy to achieve, let’s think a bit how a regular function works, we have some code and then return a value.

What if instead of returning a value we return an object?

Voila!

That’s the secret, everything inside the return object will constitute our public interface, and everything else will be private.

Function foo(){
    //this is private
    return {
        //this is public
    }
}

See how easy it is?

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>