觀察者模式

觀察者模式:

觀察者模式是設(shè)計(jì)模式的一種:由一個(gè)目標(biāo)實(shí)體(事件發(fā)送者)來(lái)維護(hù)一組的觀察者,并自動(dòng)把它們的狀態(tài)改變通知觀察者。
實(shí)現(xiàn)它需要一下幾個(gè)部分:

  • Subject: 目標(biāo)
    包含觀察者序列類,包括對(duì)觀察者的增加和刪除等功能,
  • Observer: 觀察者
    定義Update接口,根據(jù)Subject狀態(tài)定義不同函數(shù),如
    C#中對(duì)觀察者接口的定義
public interface IObserver<in T>
{
    void OnCompleted ();
    void OnError (Exception error);
    void OnNext (T value);
}
  • ConcreteSubject: 具體目標(biāo)(Subject的子類)
    把狀態(tài)變化廣播通知給所有具體觀察者,保存具體觀察者的狀態(tài)
  • ConcreteObserver: 具體觀察者(Observer的子類)
    存儲(chǔ)ConcreteSubject的引用(隨時(shí)知道具體目標(biāo)的狀態(tài)發(fā)生改變),實(shí)現(xiàn)各種狀態(tài)對(duì)應(yīng)的Update方法使?fàn)顟B(tài)與具體目標(biāo)保持一致

javascript 實(shí)現(xiàn)

  1. 觀察者序列建模,實(shí)現(xiàn)一個(gè)observerList,包括方法:Add,Empty,Count,Get,Insert,IndexOf,RemoveIndexAt
function ObserverList(){
  this.observerList = [];
}

ObserverList.prototype.Add = function( obj ){
  return this.observerList.push( obj );
};

ObserverList.prototype.Empty = function(){
  this.observerList = [];
};

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.Insert = function( obj, index ){
  var pointer = -1;

  if( index === 0 ){
    this.observerList.unshift( obj );
    pointer = index;
  }else if( index === this.observerList.length ){
    this.observerList.push( obj );
    pointer = index;
  }

  return pointer;
};

ObserverList.prototype.IndexOf = function( obj, startIndex ){
  var i = startIndex, pointer = -1;

  while( i < this.observerList.length ){
    if( this.observerList[i] === obj ){
      pointer = i;
    }
  }
i++;
  }
  return pointer;
};

ObserverList.prototype.RemoveIndexAt() = function( index ){
  if( index === 0 ){
    this.observerList.shift();
  }else if( index === this.observerList.length -1 ){
    this.observerList.pop();
  }
};


// Extend an object with an extension
//可以給觀察者添加事件函數(shù)
function extend( extension, obj ){
  for ( var key in extension ){
    obj[key] = extension[key];
  }
}
  1. 實(shí)現(xiàn)一個(gè)管理ObserverList的目標(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 );
  }
};
  1. 聲明一個(gè)觀察者,Update方法可以被根據(jù)具體的客戶行為重新
// The Observer
function Observer(){
  this.Update = function(){
    // ...
  };
}

測(cè)試代碼:
html

<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox"/>
<div id="observersContainer"></div>

** 腳本代碼**

// 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( new Subject(), controlCheckbox );

// Clicking the checkbox will trigger notifications to its observers
controlCheckbox["onclick"] = new 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( new Observer(), check );

  // 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 );
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容