##Singleton模式 ###总结 在JavaScript中, Singleton充当共享资源命名空间, 从全局命名空间中隔离出代码实现, 从而为函数提供单一访问点 ###例子 eg1. var singleton = (function(){ //保持单例的一个引用 var instance; //init返回的对象是单例 function init(){ //Singleton function privateFunc(){} var privateVar = ""; var privateRandomNumber = Math.random();
//公有接口与变量 具体可见模块模式
return {
publicFunc:function(){},
publicProperty:"",
getRandomNumber:function(){}
}
};
return {
getInstance:function(){
if(!instance) {
instance = init();
}
return instance;
}
}
})();
eg2.
singleton.getInstance = function() {
if(this._instance == null){
if(isFoo()){
this._instance = new FooSingleton();
}else {
this._instance = new BasicSingleton();
}
}
return this._instance;
}
###分析 适用性 1. eg.1 只有一个实例且用户可以从一个众所周知的访问点访问它 2. eg.2 该唯一实例应该是通过子类化可扩展的, 客户应该无需更改代码就能使用一个扩展的实例