1. 程式人生 > >設計模式——觀察者和釋出訂閱模式

設計模式——觀察者和釋出訂閱模式

最近在學習設計模式,本文就同一個例子對觀察者和釋出訂閱進行探討。

觀察者模式

    比較概念的解釋是,目標和觀察者是基類,目標提供維護觀察者的一系列方法,觀察者提供更新介面。具體觀察者和具體目標繼承各自的基類,然後具體觀察者把自己註冊到具體目標裡,在具體目標發生變化時候,排程觀察者的更新方法。

舉個例子

    比如有個“天氣中心”的具體目標A,專門監聽天氣變化,而有個顯示天氣的介面的觀察者B,B就把自己註冊到A裡,當A觸發天氣變化,就排程B的更新方法,並帶上自己的上下文。

//觀察者列表
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 );
};

//目標
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 );
  }
};

//觀察者
function Observer(){
  this.update = function(){
    // ...
  };
}

釋出訂閱模式

    訂閱者把自己想訂閱的事件註冊到排程中心,當該事件觸發時候,釋出者釋出該事件到排程中心(順帶上下文),由排程中心統一排程訂閱者註冊到排程中心的處理程式碼。

舉個例子

    比如有個介面是實時顯示天氣,它就訂閱天氣事件(註冊到排程中心,包括處理程式),當天氣變化時(定時獲取資料),就作為釋出者釋出天氣資訊到排程中心,排程中心就排程訂閱者的天氣處理程式。


var pubsub = {};
(function(myObject) {
    // Storage for topics that can be broadcast
    // or listened to
    var topics = {};
    // An topic identifier
    var subUid = -1;
    // Publish or broadcast events of interest
    // with a specific topic name and arguments
    // such as the data to pass along
    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 ));

總結:

釋出/訂閱模式有一個排程中心,所有的事件經過排程中心,直接到了訂閱者(類似微博釋出和粉絲訂閱)

觀察者模式則是拆分出目標(Subject )和觀察者(ObserverList)兩個類,分別做管理(有依賴關係)

另外,沒必要糾結 釋出/訂閱模式 和 觀察者模式的區別,事實上,這兩個模式非常相似,甚至可以相互替換,至於是否需要將 Subject 和 ObserverList 抽象成兩個類來處理,答案也不是必須的,軟體工程很重要的一點就是程式碼要怎麼拆分,要拆分到什麼粒度都是沒有標準答案的。