一、实现一个单例并不复杂,无非就是用一个变量标志当前是否已经为某个类创建过对象,如果是,下次获取该类的实例时,直接返回之前创建的对象。下面简单实现一个标准的单例模式。
var Singleton = function (name) {
this.name = name;
this.instance = null;
};
Singleton.prototype.getName = function(){
console.log(this.name);
};
Singleton.getInstance = function(name) {
//console.log(this.instance);
if(!this.instance){
this.instance = new Singleton(name);
}
return this.instance;
};
var a = Singleton.getInstance('aa');
var b = Singleton.getInstance('bb');
console.log(b === s); //true
<b>二、如果引进代理模式,单例模式的代码指责就更情清晰了。</b>
var CreateDiv = function (html) {
this.html = html;
this.init();
};
CreateDiv.prototype.init = function() {
var div = document.createElement('div');
div.innerHTML = this.html;
document.body.appendChild(div);
};
var ProxySingletonCreateDiv = (function(){
var instance;
return function(html) {
if(!instance){
instance = new CreateDiv(html);
}
return instance;
}
})();
var a= new ProxySingletonCreateDiv('aa');
var b = new ProxySingletonCreateDiv('bb');