singleton design pattern example in javascript

const Singleton = (function () {
    let instance;
 
    function createInstance() {
        const object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

const object1 = singleton.getInstance();
const object2 = singleton.getInstance();

console.log(object1 === object2); //true

No comments:

Post a Comment