Singleton Pattern

At first, it would seem that the singleton pattern is similar to the module/revealing module pattern where we create only one instance of the object. However, the difference here is we can delay the instantiation of the object, i.e. based on the requirement.

The singleton pattern restricts the instance of an object (class) to one. Here is how we create a singleton object.

var singletonObject = (function () {
    var _instance = null;
    
    // the actual object
    function myModule () {
        var _privateVar = "JS";
        var _privateFunc = function () {};
        var _randomNum = Math.floor(Math.random () * 99);
        var config = {
            locale: "en-UK",
            timezone: "GMT"
        }
        return {
            getLocale: function () {
                return this.locale;
            },
            getRandomNumber: function () {
                return _randomNum;
            }
        }
    };
    return {
        getInstance: function () {
            if (!_instance) {
                _instance = myModule ();
            }
            return _instance;
        }
    }
})();

var obj1 = singletonObject.getInstance ();
var obj2 = singletonObject.getInstance ();

obj1.getRandomNumber () === obj2.getRandomNumber (); // prints true

We are using the help of a random number to prove that we get the same instance every time we create (get) an instance of the object. When we execute the getInstance function, it checks the value of _instance (private variable, not accessible globally). If it’s value is false (null) as declared initially, we execute the myModule function and, it gets the value returned by the myModule object. We can also use the constructor pattern to create an instance of the object.

We can also get rid of IIFE here, and create a normal construct function. Then create the object using new operator and get the instance using the getInstance function.