- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 602字
- 2021-07-09 19:07:38
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.
- Learning Cython Programming(Second Edition)
- Photoshop智能手機(jī)APP UI設(shè)計(jì)之道
- SQL學(xué)習(xí)指南(第3版)
- Java入門很輕松(微課超值版)
- Machine Learning with R Cookbook(Second Edition)
- 深入淺出Windows API程序設(shè)計(jì):編程基礎(chǔ)篇
- Learning Linux Binary Analysis
- 飛槳PaddlePaddle深度學(xué)習(xí)實(shí)戰(zhàn)
- C++寶典
- Practical Game Design with Unity and Playmaker
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- 詳解MATLAB圖形繪制技術(shù)
- Flask Web開發(fā):基于Python的Web應(yīng)用開發(fā)實(shí)戰(zhàn)(第2版)
- Hack與HHVM權(quán)威指南
- After Effects CC技術(shù)大全