Javascript Singleton pattern

Javascript Singleton pattern

20. 12. 2013

Singleton pattern riesi problem, kedy je potrebne mat len jednu instanciu triedy.

Rozdiel oproti statickym triedam (alebo objektom) je, ze mozeme oddialit jeho inicializaciu, pretoze zatial nemame dostupne informacie, ktore mu chceme posunut.

Navrhovy vzor singleton teda vyzera takto:

var Singleton = (function () {
    var instance;

    function init() {
        var privatePremenna = "hodnota";
        var privateMetoda = function () {
            // ...
        };

        return {
            publicPremenna: "hodnota",
            publicMetoda: function () {
                // ...
            }
        };
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();

K instancii singletonu pristupujeme pomocou metody getInstance():

var singleton1 = Singleton.getInstance();
var singleton2 = Singleton.getInstance();

Mozeme otestovat ci ide o 1 instanciu:

console.log(singleton1 === singleton2); // true
comments powered by Disqus