Friday 21 October 2011

Creational Design Pattern - The Singleton Pattern

A singleton is a class which only allows a single instance of itself to be created, and usually give simple access to that instance, hence the name single-ton. Singletons don’t allow any parameters to be specified when creating the instance because a second request for an instance but with a different parameter could cause problems. If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.

There are different ways of implementing the singleton pattern in any language, however for this post; I am going to show you how to implement it in JavaScript. With JavaScript, singletons serve as a namespace provider, which isolate implementation code from the global namespace so as to provide single point of access for functions.
The singleton doesn’t provide a way for code that doesn’t know about a previous reference to the singleton to easily retrieve it – it is not the object or class that is returned by a singleton, it is a structure. For instance, closured variables are not actually closures but the function scope that provides the closure is the closure.
In its simplest form, a singleton in JS can be an object literal grouped together with its related methods and properties as follows:
var mySingleton  = {

Name:”Tendai”,
Surname:”Bepete”,
getFullname:function(){
      return this.Name + “ “ + this.Surname;
}

};

You can extend this further by adding private members and methods to the singleton by encapsulating variable and function declarations inside a closure:
var mySingleton = function(){
          var privateAge = 18; //something private like your age or salary
          function showPrivateAge(){
               console.log(privateAge);
          }     
return{
         showAge:function(){ // you can now make it public knowledge
             showPrivateAge();
         },
         Name:”Tendai”, //this the public can see
         Surname:”Bepete”,
         getFullname:function(){
            return this.Name + “ “ + this.Surname;
        }
} ;

};

var single = mySingleton();
single.showAge(); // logs something private - age;
console.log(single.Name); // logs Name;
Now let us consider a situation where the singleton is instantiated when it is needed.


























Calling public methods is easy as follows: mySingleton.getInstance().getFullname();

How can the singleton pattern be useful? It is useful when exactly one object is needed to coordinate patterns across the system. Here is an example:

























var singletonTest = SingletonTester.getInstance({pointX:20});
console.log(singletonTest.PointX); // outputs 20

Hope this has been helpful. Welcome to comments and suggestion.