// 单个例子的模式 demo1
function singleCase (name){
this.name = name;
}
singleCase.prototype.sayHi = function(){
alert(this.name);
}
let getInstance = (function(){
var instance = null;
return function(name) {
if(!instance) { //相当于一个一次性阀门,只能实例化一次
instance = new singleCase(name);
}
return instance;
}
})();
let one = getInstance("one");
let two = getInstance("two");
// 单例模式 demo2
function Single (name){
this.name = name;
}
Single.prototype.say = function(){
alert(12);
}
Single.getInstance = function (...args){
if(this.instance){
return this.instance;
}
this.instance = new Single(...args)
return this.instance;
}
let a1 = Single.getInstance("a1")
let a2 = Single.getInstance("a2")