要說起學(xué)習(xí)設(shè)計(jì)模式的動(dòng)機(jī)實(shí)際上是為了準(zhǔn)備面試,慚愧臉,但是也正是因?yàn)橐嬖囁源偈刮胰W(xué)習(xí),今天學(xué)習(xí)的就是觀察者模式和發(fā)布訂閱模式。
說起這兩個(gè)模式確實(shí)很像,為了弄懂其中的不同點(diǎn)確實(shí)也花了不少功夫,主要參考了這篇博文觀察者模式與發(fā)布/訂閱模式區(qū)別,另外一篇就是曾探的《JavaScript設(shè)計(jì)模式與開發(fā)實(shí)踐》一書中的《發(fā)布訂閱模式》。兩者結(jié)合大有所獲。
觀察者模式
首先來談?wù)動(dòng)^察者模式,在觀察者模式中,有兩個(gè)角色一個(gè)是Subject,用來維護(hù)一個(gè)observer列表,另一個(gè)角色就是Observer(觀察者),在Observer中定義了一個(gè)具體的update方法,用來執(zhí)行相關(guān)操作。整個(gè)過程就是當(dāng)某個(gè)值發(fā)生變化后,Subject調(diào)用notify方法(實(shí)際就是循環(huán)調(diào)用observerList中每個(gè)observer的update方法,并把新的值作為update的參數(shù)傳遞進(jìn)去)。從中我們可以看出在Subject中直接調(diào)用了Observer中的方法,也就是說Subject和Observer的聯(lián)系實(shí)際上是非常緊密的。
舉個(gè)例子,現(xiàn)在有一個(gè)房東他要租房子,當(dāng)有空房子的時(shí)候,他就會(huì)去通知曾經(jīng)來詢問的租戶,那么這個(gè)時(shí)候房東就是直接知道租客的電話和需求(要住什么樣的房子)的,也就是此時(shí)房東和租客之間實(shí)際上是存在聯(lián)系的。
大致的流向圖就像下面。
代碼如下:
//觀察者列表
function ObserverList(){
this.observerList = [];
}
ObserverList.prototype.add = function( obj ){
return this.observerList.push( obj );
};
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.indexOf = function( obj, startIndex ){
var i = startIndex;
while( i < this.observerList.length ){
if( this.observerList[i] === obj ){
return i;
}
i++;
}
return -1;
};
ObserverList.prototype.removeAt = function( index ){
this.observerList.splice( index, 1 );
};
//目標(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 );
}
};
//觀察者
function Observer(){
this.update = function(){
// ...
};
}
發(fā)布訂閱模式
前面說到Subject和Observer聯(lián)系是非常緊密的,因?yàn)槲覀円赟ubject中調(diào)用Observer中的方法。那么發(fā)布訂閱模式就可以解耦合,把調(diào)用的任務(wù)交給一個(gè)調(diào)度中心(中介),讓調(diào)度中心去通知各個(gè)訂閱者。
接著上面的例子。房東有錢后,自己變懶了,他不想每次有房源后,自己還要親自打電話通知之前預(yù)留電話想要租房的租客,因?yàn)樽约哼€要記住那些的租客的電話和需求(有錢了不想干這些活,我要躺著賺錢)。于是他就找到了中介,每次空出房子后,直接告訴中介我這里有什么樣的房子,中介這里記錄著哪些租客有著什么樣的需求,中介再去聯(lián)系有這樣需求的租客。那么這里房東和未來可能的租客之間是沒有聯(lián)系的,房東從此不用自己再去親自打電話去通知每一個(gè)有著這樣需求的租客,只需要告訴中介一個(gè)人就行,中介去通知。那么整個(gè)過程就如下面這樣
var pubsub = {};
(function(myObject) {
// Storage for topics that can be broadcast
// or listened to
var topics = {};
// An topic identifier
var subUid = -1;
// Publish or broadcast events of interest
// with a specific topic name and arguments
// such as the data to pass along
myObject.publish = function( topic, args ) {
if ( !topics[topic] ) {
return false;
}
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func( topic, args );
}
return this;
};
// Subscribe to events of interest
// with a specific topic name and a
// callback function, to be executed
// when the topic/event is observed
myObject.subscribe = function( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = ( ++subUid ).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
// Unsubscribe from a specific
// topic, based on a tokenized reference
// to the subscription
myObject.unsubscribe = function( token ) {
for ( var m in topics ) {
if ( topics[m] ) {
for ( var i = 0, j = topics[m].length; i < j; i++ ) {
if ( topics[m][i].token === token ) {
topics[m].splice( i, 1 );
return token;
}
}
}
}
return this;
};
}( pubsub ));
這里為什么要用一個(gè)立即執(zhí)行函數(shù)傳遞一個(gè)對(duì)象進(jìn)去,因?yàn)槲覀兛赡苡卸鄠€(gè)中介,每多一個(gè)中介,我們都會(huì)動(dòng)態(tài)的去添加一些方法(即告訴中介如何去運(yùn)作)。subUid就是用于方便取消訂閱操作的,假如有一天你租到了自己滿意的房子,你就要打電話告訴中介,不要再給我這個(gè)號(hào)碼打電話了,我已經(jīng)租到房子了。(不然天天都要被中介騷擾了)
總結(jié):觀察者模式和發(fā)布訂閱模式的區(qū)別應(yīng)該就是當(dāng)有房源消息的時(shí)候,到底是誰(shuí)來通知租客,觀察者是房東自己本人,而發(fā)布訂閱則是中介。
最后(歡迎大家關(guān)注我)
DJL簫氏個(gè)人博客
博客GitHub地址
簡(jiǎn)書
掘金
如果你覺得有所收獲的話,歡迎點(diǎn)贊,歡迎到我的github上面star一下。