观察者模式
优点
- 需要对应用的各个组件有一个较深的思考
- 帮助我们减少依赖
- 帮助我们减少耦合
缺点
- 检查程序完整性可能会比较困难
- 从订阅者到发布者的切换可能开销比较大
var Subject = ( function( window, undefined ) {
function Subject() {
this._list = [];
}
Subject.prototype.observe = function observeObject( obj ) {
console.log( 'added new observer' );
this._list.push( obj );
};
Subject.prototype.unobserve = function unobserveObject( obj ) {
for( var i = 0, len = this._list.length; i < len; i++ ) {
if( this._list[ i ] === obj ) {
this._list.splice( i, 1 );
console.log( 'removed existing observer' );
return true;
}
}
return false;
};
Subject.prototype.notify = function notifyObservers() {
var args = Array.prototype.slice.call( arguments, 0 );
for( var i = 0, len = this._list.length; i < len; i++ ) {
this._list[ i ].update.apply( null, args );
}
};
return Subject;
} )( window );
function StockGrabber() {
var subject = new Subject();
this.addObserver = function addObserver( newObserver ) {
subject.observe( newObserver );
};
this.removeObserver = function removeObserver( deleteObserver ) {
subject.unobserve( deleteObserver );
};
this.fetchStocks = function fetchStocks() {
var stocks = {
aapl : 167.00,
goog : 243.67,
msft : 99.34
};
subject.notify( stocks );
};
}
var StockUpdaterComponent = {
update : function() {
console.log( '"update" called on StockUpdater with: ', arguments );
}
};
var StockChartsComponent = {
update : function() {
console.log( '"update" called on StockCharts with: ', arguments );
}
};
var stockApp = new StockGrabber();
stockApp.addObserver( StockUpdaterComponent );
stockApp.fetchStocks();
stockApp.addObserver( StockChartsComponent );
stockApp.fetchStocks();
stockApp.removeObserver( StockUpdaterComponent );
stockApp.fetchStocks();
stockApp.removeObserver( StockChartsComponent );
stockApp.fetchStocks();