Skip to content

Instantly share code, notes, and snippets.

@zD98
Created March 14, 2016 01:37
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/38b15cb0c6fe9da1a69b to your computer and use it in GitHub Desktop.
Save zD98/38b15cb0c6fe9da1a69b to your computer and use it in GitHub Desktop.
设计模式

##Observer模式 ###总结 一个对象(Subject)维持一系列依赖于它的对象(Observer), 将有关状态变更自动通知给它们。 ###例子 eg. //extend 用于拓展Subject , Observer function extend(obj,extension){ for (var key in obj){ extension[key] = obj[key]; } } //私有类 Subject中的观察者列表 封装对数组的操作 function ObserverList(){ this.observerList = []; } ObserverList.prototype.Add = function(obj) {} ObserverList.prototype.Empty = function () {} ObserverList.prototype.Count = function() {} ObserverList.prototype.Get = function(index) {} ObserverList.prototype.Insert = function(obj, index){} ObserverList.prototype.IndexOf = function(obj, startIndex){} ObserverList.prototype.RemoveIndexAt() = function(index){}

	//Subject 目标类  更新动态 to observers
	function Subject(){
		this.observers = new ObserverList();
	}
	
	Subject.prototype.AddObserver = function(observer){}
	Subject.prototype.removeObserver = function (observer) {}
	//向所有依赖的观察者发布消息
	Subject.prototype.Notify = function (context){
		var observerCount = this.observers.Count();
		for(var i =0;i<observerCount;i++){
			this.observers.Get(i).Update(context);
		}
	}
	//观察者
	function Observer(){
		this.Update = function(){};
	}

###分析 优点: 1. 具体的观察者与目标是对Observer与Subject 的继承 2. Observer模式要求观察者必须依赖于目标 3. 系统解耦和 缺点: 1. 事件发布者需要自身是一个subject, 解耦不是很理想 2. 当存在多个subject时会影响性能

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