最近项目不太忙,难得有时间看看书,平时挺喜欢js这门语言。也看过很多高级教程,觉得自己还是比较热衷于js的设计模式。这一次重温一下《JavaScript设计模式与开发实践》,开篇为单例模式。
alert(this.name);
};
Singleton.getInstance = function(){
if(!this.instance){
this.instance = new Singleton(name);
}
return this.instance;
};
var a = Singleton.getInstance("amy");
var b = Singleton.getInstance("ben");
alert(a === b);
// ------------singleton-02----------------
/写法2/
var Singleton = function(name){
this.name = name;
}
Singleton.prototype.getName = function(){
return this.name;
}
Singleton.getInstance = (function(){
var instance = null;
return function(name){
if(!instance){
instance = new Singleton(name);
}
return instance;
}
})();
var a = Singleton.getInstance("amy");
var b = Singleton.getInstance("ben");
alert(a === b);
// ------------singleton03-----------
/写法3/
var Singleton = (function(){
var instance;
return function(name){
if(instance){
return instance;
}
this.name = name;
instance = this;
}
})();
var a = new Singleton("amy");
var b = new Singleton("ben");
alert(a === b);
//---------------- 示例 ---------------
var getSingleton = function(fn) {
var result;
return function() {
if(!result) {
result = fn.apply(this,arguments);
}
return result;
}
};
var getSingletonVip = (function() {
var instance;
return function(fn) {
return instance || (instance = fn.apply(this,arguments));
}
})();
var createLoginUser = function() {
var div = document.createElement("div");
div.innerHTML = '这是登录框';
document.body.appendChild(div);
return div;
};
var createInfoGrid = function() {
var div = document.createElement("div");
div.innerHTML = '这是列表信息框';
document.body.appendChild(div);
return div;
};
//--执行singleton1
var createUserDiv = getSingleton(createLoginUser);
createUserDiv();
createUserDiv();
//--执行singleton2
getSingletonVip(createLoginUser);
getSingletonVip(createLoginUser);