// 方式1
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("a");
var b = Singleton.getInstance("b");
a === b // true
// 方式2
var Singleton = function(name) {
this.name = name;
};
Singleton.prototype.getName = function() {
alert(this.name)
}
Singleton.getInstance = (function(name) {
var instance = null;
return function(name) {
if(!this.instance) {
this.instance = new Singleton(name)
}
}
return this.instance;
})();
var a = Singleton.getInstance("a");
var b = Singleton.getInstance("b");
a === b // true
// 缺点:使用者需要知道使用getInstance方法创建单例类
透明的单例模式
var Singleton = (function(){
var instance = null;
var Singleton = function() {
if(instance) {
return instance;
}
return instance = this;
}
// 原型链方法
Singleton.prototype
return Singleton;
})();
var a = Singleton.getInstance("a");
var b = Singleton.getInstance("b");
a === b // true
// 缺点: 程序复杂
js中的单例模式
// 单例即对象,使用对象就是单例了
var a = {
get: function() {
}
}
惰性单例
var getSingle = (function(fn) {
var result;
return function(fn){
return result || (result = fn.apply(this,arguments))
}
})();
// 创建iframe
getSingle(function() {
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);
return iframe
})