一、实现单例模式
var Singleton = function(name){
this.name = name;
this.instance = null;
};
Singleton.prototype.getName = function(){
alert(this.name);
};
Singleton.getInstance = function(name){
if(!this.instance){
this.instance = new Singleton(name);
}
return this.instance;
};
var a = Singleton.getInstance('tiany1');
var b = Singleton.getInstance('tiany2');
alert(a===b); //true
或者
var Singleton = function(name){
this.name = name;
this.instance = null;
};
Singleton.prototype.getName = function(){
alert(this.name);
};
Singleton.getInstance = (function(name){
var instance = null;
return function(name){
if(!instance) {
instance = new Singleton(name);
}
return instance;
}
})();
var a = Singleton.getInstance('tiany1');
var b = Singleton.getInstance('tiany2');
alert(a===b); //true
二、透明的单例模式
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('tiany1'); //生成<div>tiany1</div>
var b = new CreateDiv('tiany2');
alert(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);
};
//接下来引入代理类 proxySingletonCreateDiv
var proxySingletonCreateDiv = (function(){
var instance;
return function(html){
if(!instance){
instance = new CreateDiv(html);
}
return instance;
}
})();
var a = new proxySingletonCreateDiv('tiany1'); //生成<div>tiany1</div>
var b = new proxySingletonCreateDiv('tiany2');
alert(a===b); //true
四、JavaScript中的单例模式
在JavaScript中创建对象的方法非常简单,既然我们只需要“唯一”的对象,那我们为它先创建一个“类”。
单例模型的核心是 ** 确保只有一个实例,并提供全局访问**
1、使用命名空间
var namespace1={
a: function(){
alert(1);
},
b: function(){
alert(1);
}
};
2、使用闭包封装私有变量
var user = (function(){
var _name = 'tiany',
_age = 28;
return{
getUserInfo : function(){
return _name+"-"+_age;
}
}
})();
五、惰性单例
惰性单例指的是在需要的时候才创建对象实例
var LazySingle = ( function () {
// 单例引用
var _instance = null;
// 单例
function Single() {
return {
// 这里定义私有属性和方法
publicMethod : function () {},
publicProperty : '1.0'
}
}
// 获取单例接口
return function () {
// 如果为创建单例将创建单例
if ( ! _instance ) {
_instance = Single();
}
// 返回单例
return _instance;
}
} )();
网友评论