javascript单例模式
单例模式:一个类只有一个实例,并提供一个访问它的全局访问点
1.面向对象版的基于类的单例
创建唯一的div节点
var createDiv = (function() {
var instance;
var createDiv = function(html) {
if (instance) return instance;
this.html = html;
this.init();
return instance = this;
};
createDiv.prototype.init = function() {
var div = document.createElement('div');
div.innerHTML = this.html;
document.body.appendChild(div);
};
return createDiv;
}());
var a = new createDiv('test1');
var b = new createDiv('test2');
console.log(a === b); // true
代理类实现单例将创建单例和管理单例分离
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 ProxySingleton = (function(){
var instance;
return function(html) {
if (!instance) {
instance = new createDiv(html);
}
return instance;
}
}());
var a = new ProxySingleton('test1');
var b = new ProxySingleton('test2');
console.log(a === b); // true
2. javascript中的单例模式
点击登陆按钮时,创建登陆浮窗并弹出,浮窗唯一。之后再点击,操作已经存在的浮窗
惰性单例:需要的时候才创建对象
var createLoginLayer = (function() {
var div;
return function() {
if (!div) {
div = document.createElement('div');
div.innerHTML = 'login';
div.style.display = 'none';
document.body.appendChild(div);
}
return div;
}
}());
document.getElementById('login').onclick = function() {
var loginLayer = createLoginLayer();
loginLayer.style.display = 'block';
}
通用的惰性单例,将创建单例和管理单例分离
var createLoginLayer = function() {
div = document.createElement('div');
div.innerHTML = 'login';
div.style.display = 'none';
document.body.appendChild(div);
return div;
}
var getSingle = function(fn) {
var result;
return function() {
return result || (result = fn.apply(this, arguments));
}
};
var createSingleLoginLayer = getSingle(createLoginLayer);
document.getElementById('login').onclick = function() {
var loginLayer = createSingleLoginLayer();
loginLayer.style.display = 'block';
}