加载中...

中介者模式


中介者模式

字典中中介者的定义是,一个中立方,在谈判和冲突解决过程中起辅助作用。在我们的世界,一个中介者是一个行为设计模式,使我们可以导出统一的接口,这样系统不同部分就可以彼此通信。

如果系统组件之间存在大量的直接关系,就可能是时候,使用一个中心的控制点,来让不同的组件通过它来通信。中介者通过将组件之间显式的直接的引用替换成通过中心点来交互的方式,来做到松耦合。这样可以帮助我们解耦,和改善组件的重用性。

在现实世界中,类似的系统就是,飞行控制系统。一个航站塔(中介者)处理哪个飞机可以起飞,哪个可以着陆,因为所有的通信(监听的通知或者广播的通知)都是飞机和控制塔之间进行的,而不是飞机和飞机之间进行的。一个中央集权的控制中心是这个系统成功的关键,也正是中介者在软件设计领域中所扮演的角色。

从实现角度来讲,中介者模式是观察者模式中的共享被观察者对象。在这个系统中的对象之间直接的发布/订阅关系被牺牲掉了,取而代之的是维护一个通信的中心节点。

也可以认为是一种补充-用于应用级别的通知,例如不同子系统之间的通信,子系统本身很复杂,可能需要使用发布/订阅模式来做内部组件之间的解耦。

另外一个类似的例子是DOM的事件冒泡机制,以及事件代理机制。如果系统中所有的订阅者都是对文档订阅,而不是对独立的节点订阅,那么文档就充当一个中介者的角色。DOM的这种做法,不是将事件绑定到独立节点上,而是用一个更高级别的对象负责通知订阅者关于交互事件的信息。

基础的实现

中间人模式的一种简单的实现可以在下面找到,publish()和subscribe()方法都被暴露出来使用:

  1. var mediator = (function(){
  2. // Storage for topics that can be broadcast or listened to
  3. var topics = {};
  4. // Subscribe to a topic, supply a callback to be executed
  5. // when that topic is broadcast to
  6. var subscribe = function( topic, fn ){
  7. if ( !topics[topic] ){
  8. topics[topic] = [];
  9. }
  10. topics[topic].push( { context: this, callback: fn } );
  11. return this;
  12. };
  13. // Publish/broadcast an event to the rest of the application
  14. var publish = function( topic ){
  15. var args;
  16. if ( !topics[topic] ){
  17. return false;
  18. }
  19. args = Array.prototype.slice.call( arguments, 1 );
  20. for ( var i = 0, l = topics[topic].length; i < l; i++ ) {
  21. var subscription = topics[topic][i];
  22. subscription.callback.apply( subscription.context, args );
  23. }
  24. return this;
  25. };
  26. return {
  27. publish: publish,
  28. subscribe: subscribe,
  29. installTo: function( obj ){
  30. obj.subscribe = subscribe;
  31. obj.publish = publish;
  32. }
  33. };
  34. }());

高级的实现

对于那些对更加高级实现感兴趣的人,以走读的方式看一看以下我对Jack Lawson优秀的Mediator.js重写的一个缩略版本.在其它方面的改进当中,为我们的中间人支持主题命名空间,用户拆卸和一个更加稳定的发布/订阅系统。但是如果你想跳过这个走读,你可以直接进入到下一个例子继续阅读。

得感谢Jack优秀的代码注释对这部分内容的协助。

首先,让我们实现认购的概念,我们可以考虑一个中间人主题的注册。

通过生成对象实体,我们稍后能够简单的更新认购,而不需要去取消注册然后重新注册它们.认购可以写成一个使用被称作一个选项对象或者一个上下文环境的函数

  1. // Pass in a context to attach our Mediator to.
  2. // By default this will be the window object
  3. (function( root ){
  4. function guidGenerator() { /*..*/}
  5. // Our Subscriber constructor
  6. function Subscriber( fn, options, context ){
  7. if ( !(this instanceof Subscriber) ) {
  8. return new Subscriber( fn, context, options );
  9. }else{
  10. // guidGenerator() is a function that generates
  11. // GUIDs for instances of our Mediators Subscribers so
  12. // we can easily reference them later on. We're going
  13. // to skip its implementation for brevity
  14. this.id = guidGenerator();
  15. this.fn = fn;
  16. this.options = options;
  17. this.context = context;
  18. this.topic = null;
  19. }
  20. }
  21. })();

在我们的中间人主题中包涵了一长串的回调和子主题,当中间人发布在我们中间人实体上被调用的时候被启动.它也包含操作数据列表的方法

  1. // Let's model the Topic.
  2. // JavaScript lets us use a Function object as a
  3. // conjunction of a prototype for use with the new
  4. // object and a constructor function to be invoked.
  5. function Topic( namespace ){
  6. if ( !(this instanceof Topic) ) {
  7. return new Topic( namespace );
  8. }else{
  9. this.namespace = namespace || "";
  10. this._callbacks = [];
  11. this._topics = [];
  12. this.stopped = false;
  13. }
  14. }
  15. // Define the prototype for our topic, including ways to
  16. // add new subscribers or retrieve existing ones.
  17. Topic.prototype = {
  18. // Add a new subscriber
  19. AddSubscriber: function( fn, options, context ){
  20. var callback = new Subscriber( fn, options, context );
  21. this._callbacks.push( callback );
  22. callback.topic = this;
  23. return callback;
  24. },
  25. ...

我们的主题实体被当做中间人调用的一个参数被传递.使用一个方便实用的calledStopPropagation()方法,回调就可以进一步被传播开来:

  1. StopPropagation: function(){
  2. this.stopped = true;
  3. },

我们也能够使得当提供一个GUID的标识符的时候检索订购用户更加容易:

  1. GetSubscriber: function( identifier ){
  2. for(var x = 0, y = this._callbacks.length; x < y; x++ ){
  3. if( this._callbacks[x].id == identifier || this._callbacks[x].fn == identifier ){
  4. return this._callbacks[x];
  5. }
  6. }
  7. for( var z in this._topics ){
  8. if( this._topics.hasOwnProperty( z ) ){
  9. var sub = this._topics[z].GetSubscriber( identifier );
  10. if( sub !== undefined ){
  11. return sub;
  12. }
  13. }
  14. }
  15. },

接着,在我们需要它们的情况下,我们也能够提供添加新主题,检查现有的主题或者检索主题的简单方法:

  1. AddTopic: function( topic ){
  2. this._topics[topic] = new Topic( (this.namespace ? this.namespace + ":" : "") + topic );
  3. },
  4. HasTopic: function( topic ){
  5. return this._topics.hasOwnProperty( topic );
  6. },
  7. ReturnTopic: function( topic ){
  8. return this._topics[topic];
  9. },

如果我们觉得不再需要它们了,我们也可以明确的删除这些订购用户.下面就是通过它的其子主题递归删除订购用户的代码:

  1. RemoveSubscriber: function( identifier ){
  2. if( !identifier ){
  3. this._callbacks = [];
  4. for( var z in this._topics ){
  5. if( this._topics.hasOwnProperty(z) ){
  6. this._topics[z].RemoveSubscriber( identifier );
  7. }
  8. }
  9. }
  10. for( var y = 0, x = this._callbacks.length; y < x; y++ ) {
  11. if( this._callbacks[y].fn == identifier || this._callbacks[y].id == identifier ){
  12. this._callbacks[y].topic = null;
  13. this._callbacks.splice( y,1 );
  14. x--; y--;
  15. }
  16. }
  17. },

接着我们通过递归子主题将发布任意参数的能够包含到订购服务对象中:

  1. Publish: function( data ){
  2. for( var y = 0, x = this._callbacks.length; y < x; y++ ) {
  3. var callback = this._callbacks[y], l;
  4. callback.fn.apply( callback.context, data );
  5. l = this._callbacks.length;
  6. if( l < x ){
  7. y--;
  8. x = l;
  9. }
  10. }
  11. for( var x in this._topics ){
  12. if( !this.stopped ){
  13. if( this._topics.hasOwnProperty( x ) ){
  14. this._topics[x].Publish( data );
  15. }
  16. }
  17. }
  18. this.stopped = false;
  19. }
  20. };

接着我们暴露我们将主要交互的调节实体.这里它是通过注册的并且从主题中删除的事件来实现的

  1. function Mediator() {
  2. if ( !(this instanceof Mediator) ) {
  3. return new Mediator();
  4. }else{
  5. this._topics = new Topic( "" );
  6. }
  7. };

想要更多先进的用例,我们可以看看调解支持的主题命名空间,下面这样的asinbox:messages:new:read.GetTopic 返回基于一个命名空间的主题实体。

  1. Mediator.prototype = {
  2. GetTopic: function( namespace ){
  3. var topic = this._topics,
  4. namespaceHierarchy = namespace.split( ":" );
  5. if( namespace === "" ){
  6. return topic;
  7. }
  8. if( namespaceHierarchy.length > 0 ){
  9. for( var i = 0, j = namespaceHierarchy.length; i < j; i++ ){
  10. if( !topic.HasTopic( namespaceHierarchy[i]) ){
  11. topic.AddTopic( namespaceHierarchy[i] );
  12. }
  13. topic = topic.ReturnTopic( namespaceHierarchy[i] );
  14. }
  15. }
  16. return topic;
  17. },

这一节我们定义了一个Mediator.Subscribe方法,它接受一个主题命名空间,一个将要被执行的函数,选项和又一个在订阅中调用函数的上下文环境.这样就创建了一个主题,如果这样的一个主题存在的话

  1. Subscribe: function( topiclName, fn, options, context ){
  2. var options = options || {},
  3. context = context || {},
  4. topic = this.GetTopic( topicName ),
  5. sub = topic.AddSubscriber( fn, options, context );
  6. return sub;
  7. },

根据这一点,我们可以进一步定义能够访问特定订阅用户,或者将他们从主题中递归删除的工具

  1. // Returns a subscriber for a given subscriber id / named function and topic namespace
  2. GetSubscriber: function( identifier, topic ){
  3. return this.GetTopic( topic || "" ).GetSubscriber( identifier );
  4. },
  5. // Remove a subscriber from a given topic namespace recursively based on
  6. // a provided subscriber id or named function.
  7. Remove: function( topicName, identifier ){
  8. this.GetTopic( topicName ).RemoveSubscriber( identifier );
  9. },

我们主要的发布方式可以让我们随意发布数据到选定的主题命名空间,这可以在下面的代码中看到。

主题可以被向下递归.例如,一条对inbox:message的post将发送到inbox:message:new和inbox:message:new:read.它将像接下来这样被使用:Mediator.Publish( "inbox:messages:new", [args] );

  1. Publish: function( topicName ){
  2. var args = Array.prototype.slice.call( arguments, 1),
  3. topic = this.GetTopic( topicName );
  4. args.push( topic );
  5. this.GetTopic( topicName ).Publish( args );
  6. }
  7. };

最后,我们可以很容易的暴露我们的中间人,将它附着在传递到根中的对象上:

  1. root.Mediator = Mediator;
  2. Mediator.Topic = Topic;
  3. Mediator.Subscriber = Subscriber;
  4. // Remember we can pass anything in here. I've passed inwindowto
  5. // attach the Mediator to, but we can just as easily attach it to another
  6. // object if desired.
  7. })( window );

示例

无论是使用来自上面的实现(简单的选项和更加先进的选项都是),我们能够像下面这样将一个简单的聊天记录系统整到一起:

HTML

  1. <h1>Chat</h1>
  2. <form id="chatForm">
  3. <label for="fromBox">Your Name:</label>
  4. <input id="fromBox" type="text"/>
  5. <br />
  6. <label for="toBox">Send to:</label>
  7. <input id="toBox" type="text"/>
  8. <br />
  9. <label for="chatBox">Message:</label>
  10. <input id="chatBox" type="text"/>
  11. <button type="submit">Chat</button>
  12. </form>
  13. <div id="chatResult"></div>

Javascript

  1. $( "#chatForm" ).on( "submit", function(e) {
  2. e.preventDefault();
  3. // Collect the details of the chat from our UI
  4. var text = $( "#chatBox" ).val(),
  5. from = $( "#fromBox" ).val(),
  6. to = $( "#toBox" ).val();
  7. // Publish data from the chat to the newMessage topic
  8. mediator.publish( "newMessage" , { message: text, from: from, to: to } );
  9. });
  10. // Append new messages as they come through
  11. function displayChat( data ) {
  12. var date = new Date(),
  13. msg = data.from + " said \"" + data.message + "\" to " + data.to;
  14. $( "#chatResult" )
  15. .prepend("
  16. <p>
  17. " + msg + " (" + date.toLocaleTimeString() + ")
  18. </p>
  19. ");
  20. }
  21. // Log messages
  22. function logChat( data ) {
  23. if ( window.console ) {
  24. console.log( data );
  25. }
  26. }
  27. // Subscribe to new chat messages being submitted
  28. // via the mediator
  29. mediator.subscribe( "newMessage", displayChat );
  30. mediator.subscribe( "newMessage", logChat );
  31. // The following will however only work with the more advanced implementation:
  32. function amITalkingToMyself( data ) {
  33. return data.from === data.to;
  34. }
  35. function iAmClearlyCrazy( data ) {
  36. $( "#chatResult" ).prepend("
  37. <p>
  38. " + data.from + " is talking to himself.
  39. </p>
  40. ");
  41. }
  42. mediator.Subscribe( amITalkingToMyself, iAmClearlyCrazy );

优点&缺点

中间人模式最大的好处就是,它节约了对象或者组件之间的通信信道,这些对象或者组件存在于从多对多到多对一的系统之中。由于解耦合水平的因素,添加新的发布或者订阅者是相对容易的。

也许使用这个模式最大的缺点是它可以引入一个单点故障。在模块之间放置一个中间人也可能会造成性能损失,因为它们经常是间接地的进行通信的。由于松耦合的特性,仅仅盯着广播很难去确认系统是如何做出反应的。

这就是说,提醒我们自己解耦合的系统拥有许多其它的好处,是很有用的——如果我们的模块互相之间直接的进行通信,对于模块的改变(例如:另一个模块抛出了异常)可以很容易的对我们系统的其它部分产生多米诺连锁效应。这个问题在解耦合的系统中很少需要被考虑到。

在一天结束的时候,紧耦合会导致各种头痛,这仅仅只是另外一种可选的解决方案,但是如果得到正确实现的话也能够工作得很好。

中间人VS观察者

开发人员往往不知道中间人模式和观察者模式之间的区别。不可否认,这两种模式之间有一点点重叠,但让我们回过头来重新寻求GoF的一种解释:

“在观察者模式中,没有封装约束的单一对象”。取而代之,观察者和主题必须合作来维护约束。通信的模式决定于观察者和主题相互关联的方式:一个单独的主题经常有许多的观察者,而有时候一个主题的观察者是另外一个观察者的主题。“

中间人和观察者都提倡松耦合,然而,中间人默认使用让对象严格通过中间人进行通信的方式实现松耦合。观察者模式则创建了观察者对象,这些观察者对象会发布触发对象认购的感兴趣的事件。

中间人VS门面

不久我们的描述就将涵盖门面模式,但作为参考之用,一些开发者也想知道中间人和门面模式之间有哪些相似之处。它们都对模块的功能进行抽象,但有一些细微的差别。

中间人模式让模块之间集中进行通信,它会被这些模块明确的引用。门面模式却只是为模块或者系统定义一个更加简单的接口,但不添加任何额外的功能。系统中其他的模块并不直接意识到门面的概念,而可以被认为是单向的。


还没有评论.