JavaScript设计模式之单例模式详解

前端之家收集整理的这篇文章主要介绍了JavaScript设计模式之单例模式详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近项目不太忙,难得有时间看看书,平时挺喜欢js这门语言。也看过很多高级教程,觉得自己还是比较热衷于js的设计模式。这一次重温一下《JavaScript设计模式与开发实践》,开篇为单例模式。

Singleton.prototype.getName = function(){
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);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

猜你在找的JavaScript相关文章