Singleton Design Pattern

Ensure a class only has one instance, and provide a global point of access to it.
Gang of Four, Design Patterns
What Is It?

Simply put, a Singleton is an object which can be instantiated once-and-only once: no other instance can exist.   Repeated calls to its constructor return the same instance: period.  

In JavaScript, singletons serve as a namespace provider: jQuery does this.   Namespace singletons isolate code & protect implementation from being over-written within the global namespace.   And, of course, it provides a single-point-of-access for functions (blah, blah, blah).

Word Of Warning:

"Global point of access" should scream 'danger' to you.   In OO software design global variables and objects are often frowned upon.   You don't want the deep water objects reaching all the way up and fiddling around with stuff.   When that happens, other objects that rely on those global variables can change something and make debugging a nightmare.  

Don't laugh...it happens!


THE SIMPLEST SINGLETON

You may not know it, but you're probably already using Singletons.   Once you create an object literal in JavaScript you've reserved a little piece of memory and no other object will ever be just like that one.  

// THE SIMPLEST SINGLETON
var Singleton = {
    property1: "something",
    property2: "something else",
    method1: function () {
        console.log('hello world');
    }
};
                            

THE SINGLETON

Okay, but that really isn't what you had in mind, right?   Me neither!.  

// THE SINGLETON: Here we instantiate the singleton only when it's needed (notice the IIFE).
var Singleton = (function () {
    var instance;
    function init() {
                
        // The Singleton is created and returned here
        return {
            publicMethod: function () {
                console.log('Here we instantiate the singleton only when it was needed.');
            },
            publicProperty: 'test'
        };
    }
    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
                    
            // This returns the Singleton
            return instance;
        }
    };
})();
// Calling public methods is then as easy as:
Singleton.getInstance().publicMethod();
                            

FINALLY

While cool, the need for singletons is often a sign that we may need to re-evaluate our design.   Debugging can become a nightmare as you're constantly moving from deeply nested objects & back up to the global scope.  

However, use them right & you'll be okay!

Creational

Copyright © 2015 All Rights Reserved