javascript 设计模式1----单例模式

时间:2021-05-13 17:46:54

定义:保证一个类仅有一个实例,并提供一个访问的全局接口:

就是收:当我们 var a = new a(); var a1 = new a()是;a与a1是相等的。怎么实现呢,就是第一次实例化。第二不在实例,只是返回第一次的实例化:

附上通用的惰性单例思路:

Singleton.getInstance = (function () {
var instance = null;
return function (name) {
if( !instance){
instance = new Singleton(name);
}
return instance;
}
})()

  一个书上的登录框的例子:

var createLoginLayer = (function () {
var div;
return function () {
if(!div){
div = document.createElement('div');
div.innerHTML = '我是登录';
div.style.display = 'none';
document.body.appendChild(div);
}
return div;
}
})() document.getElementById('div1').onclick = function () {
var loginLayer = createLoginLayer();
loginLayer.style.display = 'block';
}

通用的惰性单例:

var getSingle = function (fn) {
var result;
return function () {
return result || (result = fn.apply( this,arguments));
}
}
var createLoginLayer = function () {
var div = document.createElement('div');
div.innerHTML = 'WOSHI DENGLU';
div.style.display = 'none';
document.body.appendChild(div);
return div;
} var createSingleLoginLayer = getSingle(createLoginLayer); document.getElementById('div1').onclick = function () {
var loginLayer = createSingleLoginLayer();
loginLayer.style.display = 'block';
}
//在创建一个唯一的iframe var createSingleframe = getSingle(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
return iframe;
}) document.getElementById('div1').onclick = function () {
var loginLayer = createSingleframe();
loginLayer.src = 'http://baidu.com'
}