Skip to content

Instantly share code, notes, and snippets.

@zD98
Created March 16, 2016 01:46
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/ccbcac54f2b5b02e9333 to your computer and use it in GitHub Desktop.
Save zD98/ccbcac54f2b5b02e9333 to your computer and use it in GitHub Desktop.
设计模式-中介者模式

##Mediator 模式

###总结 系统的不同部分通过该接口进行通信, 确保组件的通信是通过中心, 而不是显示通过互相引用

###例子 Mediator-复杂实现

eg.基本实现
var mediator  = (function(){
	var topics = {};
	var subscribe = function(topic,fn) {
		if(!topics[topic]) {
			topics[topic] = [];
		}
		topics[topic].push({context:this,callback:fn});
		return this;
	}

	var publish = function(topic){
		var args ;
		if(!topics[topic]){
			return false;
		}

		args =Array.prototype.slice.call(arguments,1);
		for(var i=0,l = topics[topic].length;i<l;i++){
			var subscription = topics[topic][i];
			subscription.callback.apply(Subscribe.context,args);

		}

		return this;
	}

	return {
		Publish:publish,
		Subscribe:subscribe,
		installTo:function(obj) {
			obj.subscribe = subscribe;
			obj.publish = publish
		}
	}
})();

###分析 1. 基本实现:与Pub/Sub代码相同. 2. 复杂实现:还没懂. Review后再来写 3. Mediator与Observer 区别: 1. Observer创建观察者对象, 并向订阅他们的对象发布事件 2. Mediator 限制对象严格通过Mediator进行通信 4. 问题:对Pub/Sub与Mediator的区别不了解 -理解1:Mediator是对Pub/Sub的高级封装

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