Singleton

A class of which only a single instance can exist.

  • A class has only one instance and provides a global point of access.

  • It's usage is high in javascript libraries.

  • It limits the number of instance of particular object to one, a single instance called as singleton.

  • Reduces the need for global variables because it limits namespace collision and associated risk of name collision.

  • Module pattern is manifestation(a symptom) of singleton pattern.

  • Several other patterns, such as, Factory, Prototype, and Facade are frequently implemented as Singletons when only one instance is needed.

EX:
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
 
function run() {
 
    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();
 
    alert("Same instance? " + (instance1 === instance2));  
}

Last updated