lundi 5 décembre 2016

Implementation of Singleton Pattern

I have implemented singleton pattern in javascript.

it is has follows,

var Student = (function(){
    var obj = {};
    return {
        getInstance : function(){
            return obj;
        }
    }
})();

var student1 = Student.getInstance();

student1.name = "Mejam Kinavchisko";

var student2 = Student.getInstance();
student2.age = 23;

console.log(student1.name);
console.log(student2.name);
console.log(student2.age);
console.log(student1.age);

The output is as follows,

Mejam Kinavchisko
Mejam Kinavchisko
23
23

In the above example you can see for a given instance if I add a new property "name" and assign some value, same is been reflected in the other instance.

i.e. student1 and student2 are pointing to same object.

Hence I wont to know that if I have achieved Singleton Pattern in javascript ?

Aucun commentaire:

Enregistrer un commentaire