Skip to content

Instantly share code, notes, and snippets.

@zD98
Last active March 14, 2016 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zD98/fbf50809d287d2c2167a to your computer and use it in GitHub Desktop.
Save zD98/fbf50809d287d2c2167a to your computer and use it in GitHub Desktop.
设计模式-单例模式

##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 该唯一实例应该是通过子类化可扩展的, 客户应该无需更改代码就能使用一个扩展的实例

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment