觀察者模式與發(fā)布/訂閱模式區(qū)別

轉(zhuǎn)載自:http://www.cnblogs.com/lovesong/p/5272752.html

在翻閱資料的時(shí)候,有人把觀察者(Observer)模式等同于發(fā)布(Publish)/訂閱(Subscribe)模式,也有人認(rèn)為這兩種模式還是存在差異,而我認(rèn)為確實(shí)是存在差異的,本質(zhì)上的區(qū)別是調(diào)度的地方不同。
觀察者模式
比較概念的解釋是,目標(biāo)和觀察者是基類,目標(biāo)提供維護(hù)觀察者的一系列方法,觀察者提供更新接口。具體觀察者和具體目標(biāo)繼承各自的基類,然后具體觀察者把自己注冊(cè)到具體目標(biāo)里,在具體目標(biāo)發(fā)生變化時(shí)候,調(diào)度觀察者的更新方法。
比如有個(gè)“天氣中心”的具體目標(biāo)A,專門監(jiān)聽天氣變化,而有個(gè)顯示天氣的界面的觀察者B,B就把自己注冊(cè)到A里,當(dāng)A觸發(fā)天氣變化,就調(diào)度B的更新方法,并帶上自己的上下文。

發(fā)布/訂閱模式
比較概念的解釋是,訂閱者把自己想訂閱的事件注冊(cè)到調(diào)度中心,當(dāng)該事件觸發(fā)時(shí)候,發(fā)布者發(fā)布該事件到調(diào)度中心(順帶上下文),由調(diào)度中心統(tǒng)一調(diào)度訂閱者注冊(cè)到調(diào)度中心的處理代碼。
比如有個(gè)界面是實(shí)時(shí)顯示天氣,它就訂閱天氣事件(注冊(cè)到調(diào)度中心,包括處理程序),當(dāng)天氣變化時(shí)(定時(shí)獲取數(shù)據(jù)),就作為發(fā)布者發(fā)布天氣信息到調(diào)度中心,調(diào)度中心就調(diào)度訂閱者的天氣處理程序。

總結(jié)

  1. 從兩張圖片可以看到,最大的區(qū)別是調(diào)度的地方。
    雖然兩種模式都存在訂閱者和發(fā)布者(具體觀察者可認(rèn)為是訂閱者、具體目標(biāo)可認(rèn)為是發(fā)布者),但是觀察者模式是由具體目標(biāo)調(diào)度的,而發(fā)布/訂閱模式是統(tǒng)一由調(diào)度中心調(diào)的,所以觀察者模式的訂閱者與發(fā)布者之間是存在依賴的,而發(fā)布/訂閱模式則不會(huì)。
  2. 兩種模式都可以用于松散耦合,改進(jìn)代碼管理和潛在的復(fù)用。
    附錄
    觀察者模式實(shí)現(xiàn)代碼(JavaScript版):
//觀察者列表
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 );
};

//目標(biāo)
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(){
    // ...
  };
}

發(fā)布/訂閱模式實(shí)現(xiàn)代碼(JavaScript經(jīng)典版):

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 ));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容