用在只有可以创建一个的地方
1.把create类和 真实类分开,暴露create类,隐藏真实类。以防其他开发者,new 真实类。
2.如果实例已经存在,返回。如果实例不存在,创建返回。
3.储存实例的位置,通过闭包,存在全局。
class Window {
constructor(name){
this.name = name;
}
getName(){
console.log(this.name);
}
}
let CreateWindow = (function () {
let instance;
return function (name) {
if (!instance) {
instance = new Window(name);
}
return instance;
}
})();
let w1 = new CreateWindow('zfpx1');
let w2 = new CreateWindow('zfpx2');
console.log(w1 === w2);