[POO] Créer un singleton, en JavaScript
Bonjour à tous,
Voici un exemple de constructeur, selon le design pattern Singleton :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
var Singleton, instance1, instance2;
Singleton = (function () {
var self;
self = {
instance: void null
};
return {
Singleton: function Singleton() {
if(self.instance === void null) {
self.instance = this;
self.instance.value = 0;
}
return self.instance;
}
}.Singleton;
})(); |
Démonstration :
Code:
1 2 3 4 5
|
instance1 = new Singleton();
instance2 = new Singleton();
instance2.value += 1;
console.log(instance1); // Singleton{ value: 1} |