官术网_书友最值得收藏!

The observer pattern

Let's first see the language-agnostic definition of the observer pattern. The GOF book, Design Patterns: Elements of Reusable Object-Oriented Software, defines the observer pattern as follows:

One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves.

In the observer design pattern, the subject keeps a list of objects depending on it (called observers) and notifies them when the state changes. The subject uses a broadcast to the observers to inform them of the change. Observers can remove themselves from the list once they no longer wish to be notified. Based on this understanding, we can define the participants in this pattern:

  • Subject: This keeps the list of observers and has methods to add, remove, and update observers
  • Observer: This provides an interface for objects that need to be notified when the subject's state changes

Let's create a subject that can add, remove, and notify observers:

var Subject = ( function(  ) {
  function Subject() {
    this.observer_list = [];
  }
  // this method will handle adding observers to the internal list
  Subject.prototype.add_observer = function ( obj ) {
    console.log( 'Added observer' );
    this.observer_list.push( obj );
  };
  Subject.prototype.remove_observer = function ( obj ) {
    for( var i = 0; i < this.observer_list.length; i++ ) {
      if( this.observer_list[ i ] === obj ) {
        this.observer_list.splice( i, 1 );
        console.log( 'Removed Observer' );
      }
    }
  };
  Subject.prototype.notify = function () {
    var args = Array.prototype.slice.call( arguments, 0 );
    for( var i = 0; i<this.observer_list.length; i++ ) {
 this.observer_list[i].update(args);
    }
  };
  return Subject;
})();

This is a fairly straightforward implementation of a Subject. The important fact about the notify() method is the way in which all the observer objects' update() methods are called to broadcast the update.

Now let's define a simple object that creates random tweets. This object is providing an interface to add and remove observers to the Subject via addObserver() and removeObserver() methods. It also calls the notify() method of Subject with the newly fetched tweet. When this happens, all the observers will broadcast that the new tweet has been updated with the new tweet being passed as the parameter:

function Tweeter() {
  var subject = new Subject();
  this.addObserver = function ( observer ) {
    subject.add_observer( observer );
  };
  this.removeObserver = function (observer) {
    subject.remove_observer(observer);
  };
  this.fetchTweets = function fetchTweets() {
    // tweet
    var tweet = {
      tweet: "This is one nice observer"
    };
    // notify our observers of the stock change
    subject.notify( tweet );
  };
}

Let's now add two observers:

var TweetUpdater = {
  update : function() {
    console.log( 'Updated Tweet -  ', arguments );
  }
};
var TweetFollower = {
  update : function() {
    console.log( '"Following this tweet -  ', arguments );
  }
};

Both these observers will have one update() method that will be called by the Subject.notify() method. Now we can actually add these observers to the Subject via Tweeter's interface:

var tweetApp = new Tweeter();
tweetApp.addObserver( TweetUpdater );
tweetApp.addObserver( TweetFollower );
tweetApp.fetchTweets();
tweetApp.removeObserver(TweetUpdater);
tweetApp.removeObserver(TweetFollower);

This will result in the following output:

Added observer
Added observer
Updated Tweet -   { '0': [ { tweet: 'This is one nice observer' } ] }
"Following this tweet -   { '0': [ { tweet: 'This is one nice observer' } ] }
Removed Observer
Removed Observer

This is a basic implementation to illustrate the idea of the observer pattern.

主站蜘蛛池模板: 盐城市| 博罗县| 新安县| 枞阳县| 河北省| 米泉市| 蕉岭县| 新竹市| 南丹县| 桐乡市| 阜康市| 黑河市| 桂阳县| 高台县| 乐东| 新密市| 廉江市| 河津市| 荔浦县| 斗六市| 文水县| 安庆市| 泰顺县| 江安县| 淳化县| 嘉义县| 卓尼县| 曲阜市| 布拖县| 同仁县| 宝鸡市| 许昌市| 沐川县| 临夏市| 纳雍县| 通许县| 博湖县| 牙克石市| 张北县| 吉林市| 乌恰县|