1. es6类写法的单例模式
// 1.使用静态方法去判断实例是否已有
class Singleton {
constructor(listDetail) {
this.listDetail = listDetail;
}
//静态方法
static getInstance(listDetail) {
if(!this.instance) {
this.instance = new Singleton(listDetail);
}
return this.instance;
}
}
// 2.放在构造函数中去判断
class SingleInstance {
constructor(age) {
if(!SingleInstance.instance) {
this.age = age;
SingleInstance.instance = this;
}
return SingleInstance.instance;
}
}
const s1 = new SingleInstance(12)
const s2 = new SingleInstance()
console.table(s1)
console.log(s1 === s2)
2.es5构造函数的单例模式
使用了闭包
const GlobalSingleton = (function () {
function DoObj(name, age) {
this.name = name;
this.age = age;
}
function Singleton(name, age) {
const instance = Symbol.for('instance');
if (!Singleton[instance]) {
Singleton[instance] = new DoObj(name, age);
}
return Singleton[instance];
}
return Singleton;
})();
const a = new GlobalSingleton('ha', 12);
const b = new GlobalSingleton('ha12', 23);
console.log(a);
console.log(b);