jeudi 31 août 2023

Why is this code not in a singleton pattern?

According to the design rules, a singleton pattern must exist in an instance. If I remove the line of code and return an object, will the function be a single pattern?

const singleton = (function(){
    
    let instance, 
         counter = 0;
    
    const createInstance = () => ({
        getCounter: () => counter,
        addCounter: (num) => counter += num,
    })
    
    
    return {                                    
        getInsctance: () => createInstance()  //  insctance || (insctance = createInsctance())  ????
    } 
    
})()


const r = singleton.getInsctance()
const r2 = singleton.getInsctance()

r.addCounter(12) 
r2.addCounter(32) 

singleton.counter = 100 

console.log(r2.getCounter()) // 44
console.log(r.getCounter())  // 44

Why is this feature not singleton pattern?

Aucun commentaire:

Enregistrer un commentaire