Offline
Online
Viewers

JavaScript Singleton Pattern

Singletons are quite effective when it comes to needing only a single instance of a class or object instanciated, regardless of when or who creates it. Let’s start by creating a basic class that we will later turn into a singleton:

[codesyntax lang=”javascript”]

function ValueObject(){

    var value = 100;

    this.getValue = function(){
        return value;
    }

    this.setValue = function(v){
        value = v;
    }

}

[/codesyntax]

So, now we have a simple ValueObject class, which has public members to set and get the value member. Now comes the cool part, let’s make it a singleton. So for an object to be a singleton, only a single object of that type can exists for the lifetime of the execution. To do this, we must wrap the ValueObject in an object that will obscure the ability to use the new operator in conjuction with ValueObject. We must also make the wrapper object static with a method that will return a single instance of the ValueObject class. Here’s how to do it:

[codesyntax lang=”javascript”]

var Singleton = new function(){

    var instance = null;

    this.getInstance = function(){
        //check instance and return singleton class
    }
}

[/codesyntax]

So now as we examine the above code, we see something a little out of place. The “new” operator inline with the definition of a class. Can we do that? Sure can, this forces a single instance of the Singleton class to be created at the time it is interpreted. This type of definition also gives us accessibility to methods bound to the “this” object as well, making public member methods act almost static. So let’s finish this Singleton class out, by adding our ValueObject as the singleton type returned by the getInstance method.

[codesyntax lang=”javascript”]

var Singleton = new function(){

    var instance = null;

    function ValueObject(){

        var value = 100;

        this.getValue = function(){
            return value;
        }

        this.setValue = function(v){
            value = v;
        }

    }

    this.getInstance = function(){
        if(!instance)
            instance = new ValueObject();
        return instance;
    }

}

[/codesyntax]

Now that the Singleton class is complete, we have a class which will allow for only one instance of the ValueObject class to live, with a single method for creation or returning the instance (getInstance). Now, let’s test it out:

[codesyntax lang=”javascript”]

//Assume Singleton class code above

var s = Singleton.getInstance();

alert(s.getValue()); //alerts 100

s.setValue(200);

alert(s.getValue()); //alerts 200

s = Singleton.getInstance(); //let's make sure there's only one instance
alert(s.getValue()); //alerts 200, yep...all is good!

[/codesyntax]

That’s all there is to it. Enjoy!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Affiliates