In singleton pattern, one instance of a class will be instantiated and no more. The same object is returned to all the clients that request for a new object of a singleton class. In traditional object oriented languages, this is achieved by making the constructor private and exposing a static public property which in turn returns the same instance every time.
Let’s see how this is done in javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
var singletonModule = (function () { // private property to hold the instance var instance; // private function to instantiate the object var init = function () { var random = Math.random(); // expose publicly from funtion init() return { getRandom: function () { return random; }, anotherPublicMethod: function () { //another public method } }; }; return { getInstance: function () { // check if the instance already exists. create if it does not if (!instance) { instance = init(); } return instance; } }; })(); // Usage: var m1 = singletonModule.getInstance(); var m2 = singletonModule.getInstance(); console.log(m1.getRandom() == m2.getRandom()); |
The public method getInstance() exposes the object instance. A check is done to see if an instance was created earlier. If it was created before, that same instance is used; otherwise a new instance is created and returned.
The init() function exposes the public and private methods of the instance. Private methods and properties are protected from outside access. Public methods and properties are accessible from outside, just like any other modules.
The singleton pattern is not very useful in the context of javascript in traditional webpages, as the application scope gets reset every time the page is refreshed.
However, the singleton implementations come particularly handy in Singe Page Applications commonly referred as SPA. In a SPA, the entire lifetime of the application is managed in a single page and there are no page refreshes that reset the application life cycle.