單例模式:一個(gè)類只有一個(gè)實(shí)例
實(shí)現(xiàn)
立即執(zhí)行函數(shù)實(shí)現(xiàn)
let Singleton = (function() {
let instance = null;
return function(name, age) {
if(instance) { // 存在實(shí)例直接返回
return instance;
}
instance = this; // 第一次new則保存(緩存)實(shí)例
this.name = name;
this.age = age;
};
})();
const test1 = new Singleton('jack', 11);
const test2 = new Singleton('tom', 22);
console.log(test1 == test2); // true
惰性函數(shù)實(shí)現(xiàn)(推薦)
var Singleton = function(name, age) {
let install = this;
this.name = name;
this.age = age;
Singleton = function(name) {
return install;
}
}
const test1 = new Singleton('jack', 11);
const test2 = new Singleton('tom', 22);
console.log(test1 === test2); // true