Fork me on GitHub

JavaScript 中介者模式与观察者模式有何不同?

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailmvp

感觉二者非常像,都是pub/sub机制,如何进行区分?分别在什么不同的场景中进行应用?

  • 在Obsever模式中, 不存在封装约束的单一对象。Observer 和 Subject 必须合作才能维持约束。
  • Communication(通讯)模式由观察者和目标互联的方式决定:单一目标通常有很多观察者,有时一个目标的观察者是另一个观察者的目标
  • Mediator 和 Observer  都能促进松耦合,然后Mediator 模式通过限制对象严格通过Mediator 进行通信来实现这个个目的
  • Observer 模式创建观察者对喜爱那个,观察者对象向订阅它们的对喜爱那个发布其感兴趣的事件。

在GoF的原文中是这样描述观察者模式的:

  • One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves.
  • 具体应用场景是,当subject的某个动作需要引发一系列不同对象的动作(比如你是一个班长要去通知班里的某些人),与其一个一个的手动调用触发的方法(私下里一个一个通知),不如维护一个列表(建一个群),这个列表存有你想要调用的对象方法(想要通知的人);之后每次做的触发的时候只要轮询这个列表就好了(群发),而不用关心这个列表里有谁,只用关心想让谁加入让谁退出


这个列表就叫做ObserverList,它有一些维护列表方法:

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.RemoveAt = function( index ){};

而我们的subject只用关心两件事:1.维护这个列表,2.发布事件

function Subject(){
  this.observers = new ObserverList();
}

Subject.prototype.AddObserver = function( observer ){
  this.observers.Add( observer );
};  

Subject.prototype.RemoveObserver = function( observer ){
  this.observers.RemoveAt( this.observers.IndexOf( observer, 0 ) );
};  

Subject.prototype.Notify = function( context ){
  var observerCount = this.observers.Count();
  for(var i=0; i < observerCount; i++){
    this.observers.Get(i).Update( context );  
    // 在这里假设的是列表里的每个对象都有update方法,但个人觉得这个列表里也可以是不同对象的不同方法,只要能接受当前上下文作为参数, 可以这样执行:
    // subscription.callback.apply( subscription.context, args );
  }
};

中介模式(Mediator Pattern)

让我们假设这样一个场景: 有一个Manager一声令下,需要让工人A和工人B开工,代码可以是这样的

Manager.start = function () {
    A.work();
    B.work();
}

其实还可以这么写,新增一个中介模块,这个模块有存储了Manager的常用命令比如start,stop,resume,每一个命令其实维护的也是一个列表,比如start的列表下存储了所有员工的start方法:

Mediator["start"] = [
    {
        name: 'A',
        callback: 'work'
    },
    {
        name: 'B',
        callback: 'workAgain'
    },
]

所以Manager的方法可以重写为

Manager.start = function () {
    Mediator.publish('start')   // publish 为触发命令函数,以此来触发start命令下维护的所有回调函数
}

代码细节就不展示了,主要体现这么一个机制,而如果某个员工要提交自己的work方法供老板调用的话,只要注册一下就好了

Mediator.subscribe('C', function callback() {});

 

问题是新增加一个中介模块的好处是什么?

1.低耦合!如果不是经理要让员工开始工作,是董事长怎么办,或者是部门主管怎么办,难道都要这么写

XXX.start = function () {
    A.work()
    B.work();
}

都要把A.work什么抄一遍?当然不是,只要给中介模块发出命令就好了,
2.模块之间不需要进行通信,只要负责广播和监听事件就好了
3.在模块化的javascript中,中介模块能提高可维护性:是否启动某个模块,有没有权限启动某个模块,异步加载某些模块,模块之间的依赖关系,某些模块启动失败了怎么办。这些边界条件都可以交给它来判断,而其他模块只关心实现自己逻辑就好了
最后打个比方,中介模块真的就像房屋中介一样!如果你是房东,你只需要下令一声“我要找人租房”,他们就自然会生成那个列表,你不用直接和房客打交道。

posted on 2013-07-18 21:08  【艾伦】  阅读(5359)  评论(3编辑  收藏  举报