JS设计模式 - 观察者模式与发布/订阅模式

1,832 阅读6分钟

这是我参与更文挑战的第11天,活动详情查看更文挑战

观察者模式本质上是一种对象行为模式,而 发布/订阅模式本质上是一种架构模式,强调组件的作用。

1. 观察者模式

观察者模式是一种设计模式,其中一个对象(称为主体)根据对象(观察者)维护一个对象列表,自动通知他们对状态的任何更改。

意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
动机:将一个系统分割成一系列相互协作的类有一个副作用:需要维护相关对象间的一致性。不希望为了维持一致性而使各类紧密耦合,这样会降低可重用性。

“一个或多个观察者对某个主体的状态感兴趣,并通过附加他们自己的兴趣来注册主题,当观察者感兴趣的主题发生变化时,会发送通知消息,在每个主题中调用更新方法观察者,当观察者不再对主体的状态感兴趣时,他们可以简单地分离自己。“

可能从上面的描述还不能都抓到重要的信息。接下来我们还是先看一下design pattern书中的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>The "Click the button" page</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <button id="addNewObserver">Add New Observer checkbox</button>
    <input id="mainCheckbox" type="checkbox"/>
    <div id="observersContainer"></div>
    <script type="text/javascript" src='index.js'></script>
  </body>
</html>

/*
 * Subject
 * 内部创建了三个方法,内部维护了一个ObserverList。
 */

//contructor function
function Subject(){
  this.observers = new ObserverList();
}
 
//addObserver: 调用内部维护的ObserverList的add方法
Subject.prototype.addObserver = function( observer ){
  this.observers.add( observer );
};
 
//removeObserver: 调用内部维护的ObserverList的removeat方法
Subject.prototype.removeObserver = function( observer ){
  this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};
 
//notify: 通知函数,用于通知观察者并且执行update函数,update是一个实现接口的方法,是一个通知的触发方法。
Subject.prototype.notify = function( context ){
  var observerCount = this.observers.count();
  for(var i=0; i < observerCount; i++){
    this.observers.get(i).update( context );
  }
};

/*
 * ObserverList
 * 内部维护了一个数组,4个方法用于数组的操作,这里相关的内容还是属于subject,因为ObserverList的存在是为了将subject和内部维护的observers分离开来,清晰明了的作用。
 */
function ObserverList(){
  this.observerList = [];
}
 
ObserverList.prototype.add = function( obj ){
  return this.observerList.push( obj );
};
 
ObserverList.prototype.count = function(){
  return this.observerList.length;
};
 
ObserverList.prototype.get = function( index ){
  if( index > -1 && index < this.observerList.length ){
    return this.observerList[ index ];
  }
};
 
ObserverList.prototype.indexOf = function( obj, startIndex ){
  var i = startIndex;
 
  while( i < this.observerList.length ){
    if( this.observerList[i] === obj ){
      return i;
    }
    i++;
  }
 
  return -1;
};
 
ObserverList.prototype.removeAt = function( index ){
  this.observerList.splice( index, 1 );
};

/*
 * The Observer
 * 提供更新接口,为想要得到通知消息的主体提供接口。
 */ 
function Observer(){
  this.update = function(){
    // ...
  };
}

// Extend an object with an extension
function extend( obj, extension ){
  for ( var key in extension ){
    obj[key] = extension[key];
  }
}
 
// References to our DOM elements
 
var controlCheckbox = document.getElementById( "mainCheckbox" ),
  addBtn = document.getElementById( "addNewObserver" ),
  container = document.getElementById( "observersContainer" );
 
// Concrete Subject
 
// Extend the controlling checkbox with the Subject class
extend( controlCheckbox, new Subject() );
 
// Clicking the checkbox will trigger notifications to its observers
controlCheckbox.onclick = function(){
  controlCheckbox.notify( controlCheckbox.checked );
};
 
addBtn.onclick = addNewObserver;
 
// Concrete Observer
function addNewObserver(){
  // Create a new checkbox to be added
  var check = document.createElement( "input" );
  check.type = "checkbox";
 
  // Extend the checkbox with the Observer class
  extend( check, new Observer() );
 
  // Override with custom update behaviour
  check.update = function( value ){
    this.checked = value;
  };
 
  // Add the new observer to our list of observers
  // for our main subject
  controlCheckbox.addObserver( check );
 
  // Append the item to the container
  container.appendChild( check );
}

上面的例子其实分为了下面的几个部分:
Subject:维护观察员名单,便于添加或删除观察员
Observer:为需要被通知主体的状态改变的对象提供更新接口
ConcreteSubject:向观察者广播关于状态变化的通知,存储ConcreteObservers的状态
ConcreteObserver:存储对ConcreteSubject的引用,实现Observer的更新接口,以确保状态与Subject的一致

然后我们将上面的各个部分对应到例子中去:

具体的操作流程如下:
a. 定义好主体类和观察者类
b. 类实例化成具体对象,绑定方法,观察者在主体对象里注册
c. 操作。主体分发消息给观察者。

观察者模式 (1).png
走到这里,看到的是一种什么行为呢?

观察者模式自己已经定义好观察者和主题的结构,然后由具体的主题和观察者去继承它,这也是为什么上面说的是一种对象行为模式,在定义的Subject和Observer之间已经定义好了彼此之间的联系,这是一个紧耦合的状态。

观察者为什么这么做呢,从观察者模式自己的名称来看,它的侧重点就是观察对象,观察者的状态需要随着主题的通知去发生变化,所以自己本身定义了主题和观察者之间的紧密联系。


2.发布/订阅模式

发布/订阅模式使用位于希望接收通知的对象(订阅者)和发起事件的对象(发布者)之间的主题/事件频道。这个事件系统允许代码定义特定于应用程序的事件,这些事件可以传递包含订户所需值的自定义参数 这里的想法是避免用户和发布者之间的依赖关系。这里和观察者模式就不一样了。

侧重点在于订阅者订阅事件,发布者发布信息,至于订阅者接受信息之后的处理并不关心。但是这个地方的问题在于Subject已经是项目的一个实实在在的构成部分,它不再是一个去规范行为的东西。这也是为什么一开始说是一种架构模式。

var pubsub = {};
(function(myObject) {
    // Storage for topics that can be broadcast
    // or listened to
    var topics = {};
 
    // A topic identifier
    var subUid = -1;
 
    myObject.publish = function( topic, args ) {
 
        if ( !topics[topic] ) {
            return false;
        }
 
        var subscribers = topics[topic],
            len = subscribers ? subscribers.length : 0;
 
        while (len--) {
            subscribers[len].func( topic, args );
        }
 
        return this;
    };
 
    // Subscribe to events of interest
    // with a specific topic name and a
    // callback function, to be executed
    // when the topic/event is observed
    myObject.subscribe = function( topic, func ) {
 
        if (!topics[topic]) {
            topics[topic] = [];
        }
 
        var token = ( ++subUid ).toString();
        topics[topic].push({
            token: token,
            func: func
        });
        return token;
    };
 
    // Unsubscribe from a specific
    // topic, based on a tokenized reference
    // to the subscription
    myObject.unsubscribe = function( token ) {
        for ( var m in topics ) {
            if ( topics[m] ) {
                for ( var i = 0, j = topics[m].length; i < j; i++ ) {
                    if ( topics[m][i].token === token ) {
                        topics[m].splice( i, 1 );
                        return token;
                    }
                }
            }
        }
        return this;
    };
}( pubsub ));

// A simple message logger that logs any topics and data received through our
// subscriber
var messageLogger = function ( topics, data ) {
    console.log( "Logging: " + topics + ": " + data );
};

// Subscribers listen for topics they have subscribed to and
// invoke a callback function (e.g messageLogger) once a new
// notification is broadcast on that topic
var subscription = pubsub.subscribe( "inbox/newMessage", messageLogger );
 
// Publishers are in charge of publishing topics or notifications of
// interest to the application. e.g:
 
pubsub.publish( "inbox/newMessage", "hello world!" );
 
// or
pubsub.publish( "inbox/newMessage", ["test", "a", "b", "c"] );
 
// or
pubsub.publish( "inbox/newMessage", {
  sender: "hello@google.com",
  body: "Hey again!"
});
 
// We can also unsubscribe if we no longer wish for our subscribers
// to be notified
pubsub.unsubscribe( subscription );
 
// Once unsubscribed, this for example won't result in our
// messageLogger being executed as the subscriber is
// no longer listening
pubsub.publish( "inbox/newMessage", "Hello! are you still there?" );

3. 两者之间的区别

主题与订阅者之间的联系
观察者模式是一种紧耦合的状态,而发布/订阅模式是一种松耦合的状态。

通知订阅者的方式

观察者模式是通过主题自己本身去遍历观察者,然后调用订阅者的通知方法去实现的。而发布/订阅模式是通过事件管道去通知的,其实做这个事情的主题是是事件,因为在执行具体的事件的时候,没人知道接下来执行的方法是什么吗?因为订阅/发布模式维护了所有的订阅者事件。其实二者之间就好像一个是授之以渔,另外一个是授之以鱼。

观察者模式告诉我们接下来代码运行的步骤,而订阅/发布模式就好像是自己亲自上阵将所有的事情搞好。

内部维护的内容

观察者模式维护了观察者,知道有哪些观察者在关注。订阅/发布模式则省略了这一步骤,直接维护订阅者的事件机制,直接执行具体的事件好了,至于是谁在订阅,管他的呢!

举个例子
中心是我自己,我做了两件事情,一是买了股票。二是订阅了报纸。每一天这两件事情都会发生。但是作为我来说,我的想法是什么呢?

股票开市了,这一天忙的一直盯着屏幕,生怕别跌了。对于股票这件事情,股票是主题,而我是订阅者,我们之间的关系在我看来非常重要,关系着我的钱,能不紧密吗。可是今天的行情不太好,跌了。回到家心情很低落,回到家待了一会,想起今天的报纸,没有送来,于是就打电话问一下是怎么回事?原来已经送来了,被室友领过了。于是我知道报纸送来了就行了,心情不好就不看了。对于报纸这件事来说,我关心的是今天的报纸印了,并且也送来了就行,不看就不看了。

参考

addyosmani.com/resources/e…
blog.csdn.net/elibrace/ar…
segmentfault.com/a/119000001…