Part 02: Singleton

Part 02: Singleton

Singleton is a creational design pattern. In this pattern only a single instance is created if it does not exist. If an instance exists, its reference is returned, new instance is not created. This single instance is called singleton. The value of a singleton is modified through methods. The singleton is not freed until the termination of the program.

When to use singleton:

They are useful for the co-ordination of system-wide actions from a single central place. For example Managing a connection (or a pool of connections) to a database. to ensure no connections are lost. Some other applications of singletons are logger objects or configuration settings classes.

Advantages:

  • Because singleton encapsulates its sole instance, it can have strict control over how and when clients access it.
  • It limits global namespace pollution and associated risk of name collisions.
  • Because it provides only a single accessing point for object it is easy to maintain.
  • It helps hiding dependencies.
  • It can be extended into a factory pattern.

Disadvantages:

  • This pattern reduces the potential for parallelism within a program, because to access the singleton in a multi-threaded system, an object must be serialized (by locking).

Applicability of a singleton:

In GoF book, a singleton pattern is applicable if it fulfills these conditions;

  1. There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  2. When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code.

Structure:

rsz_singleton.png

Implementation in JavaScript:
var Singleton = (function (){

  var instance = null;

  function createInstance(){
    var obj = new Object("I am the instance");
    return obj;
  }

  return {
    getInstance: function(){
      if(instance == null){
        instance = createInstance();
      }

      return instance;
    }
  }

})();

function test(){
  var instance1 = Singleton.getInstance();
  var instance2 = Singleton.getInstance();

  console.log(Object.is(instance1,instance2));
}

test();

By using an IIFE, we will be able to declare private variables and functions in it and the constructor will be hidden from the client. The getInstance is the only way to access the instance, allowing us to return same instance everytime if there is an instance present and makes a new one if there is no instance present.