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

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.

主站蜘蛛池模板: 溧水县| 策勒县| 雷波县| 南通市| 巴林右旗| 宝山区| 五峰| 宜川县| 灵山县| 宁城县| 仲巴县| 中牟县| 阿拉善盟| 涪陵区| 丽水市| 紫阳县| 龙海市| 东海县| 孟津县| 独山县| 高邑县| 广饶县| 城固县| 青龙| 盐山县| 大丰市| 莱阳市| 新安县| 平阳县| 尉氏县| 桐乡市| 阳城县| 镇赉县| 盘锦市| 左权县| 宝坻区| 东乡族自治县| 麻城市| 定陶县| 长治市| 玛多县|