觀察者模式(Observer)與發布訂閱模式(Pub/Sub)常被混為一談,但兩者有一個關鍵差異:觀察者模式中,主題知道它的觀察者是誰,並直接呼叫它們;發布訂閱模式中,發布者與訂閱者透過一個中介(事件通道)溝通,彼此完全不认识。以下把兩種都實作一遍。
先建立一個能管理觀察者的集合:
function ObserverList() {
this.observerList = [];
}
ObserverList.prototype.Add = function (obj) { return this.observerList.push(obj); };
ObserverList.prototype.Empty = function () { this.observerList = []; };
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.Insert = function (obj, index) {
var pointer = -1;
if (index === 0) { this.observerList.unshift(obj); pointer = index; }
else if (index === this.observerList.length) { this.observerList.push(obj); pointer = index; }
return pointer;
};
ObserverList.prototype.IndexOf = function (obj, startIndex) {
var i = startIndex, pointer = -1;
while (i < this.observerList.length) {
if (this.observerList[i] === obj) { pointer = i; }
i++;
}
return pointer;
};
ObserverList.prototype.RemoveIndexAt = function (index) {
if (index === 0) { this.observerList.shift(); }
else if (index === this.observerList.length - 1) { this.observerList.pop(); }
return index;
};
這一段其實就是一個手刻的陣列。原範例的 IndexOf 有個問題:它用 while 走訪但不中斷,最後記下的是最後一個相符的索引,而非第一個;RemoveIndexAt 也只處理頭尾兩個位置。實務上直接用 Array.prototype 就好:
ObserverList.prototype.Remove = function (obj) {
var i = this.observerList.indexOf(obj);
if (i > -1) this.observerList.splice(i, 1);
return i;
};
function Subject() {
this.observers = new ObserverList();
}
Subject.prototype.AddObserver = function (obj) {
this.observers.Add(obj);
};
Subject.prototype.RemoveObserver = function (observer) {
this.observers.Remove(observer);
};
Subject.prototype.Notify = function (context) {
var count = this.observers.Count();
for (var i = 0; i < count; i++) {
this.observers.Get(i).update(context);
}
};
Notify 逐一呼叫每個觀察者的 update 方法——這就是觀察者模式的耦合所在:主題必須知道觀察者有 update。
var Pubsub = {};
(function (q) {
var topics = [], subUid = -1;
q.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;
};
q.subscribe = function (topic, func) {
if (!topics[topic]) { topics[topic] = []; }
var token = (++subUid).toString();
topics[topic].push({ token: token, func: func });
return token; // 回傳權杖,日後退訂用
};
q.unsubscribe = function (token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0; i < topics[m].length; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return this;
};
}(Pubsub));
這裡的巧思是回傳一個 token 而非訂閱函式本身,退訂時只要拿 token 對照即可。發布與訂閱雙方只知道頻道名稱,彼此毫無參照——這是它比觀察者模式鬆散得多的地方。
// 訂閱
var token = Pubsub.subscribe('user:login', function (topic, data) {
console.log('有人登入了:', data.name);
});
// 發布
Pubsub.publish('user:login', { name: 'Phillip' });
// 退訂
Pubsub.unsubscribe(token);
用 Map 取代物件當儲存。topics 用空陣列 [] 初始化卻當物件用,雖然在 JS 裡可行,但語意上應該是 {} 或 new Map()。用 Map 還能避免頻道名為 __proto__ 或 constructor 時發生的原型污染。
記得處理「一邊發布一邊退訂」。原範例用 while(len--) 倒序走訪,恰好避開了 splice 造成的索引錯位,這是個好設計,值得保留。
錯誤隔離。若某個訂閱者的回呼丟出例外,整個發布流程就會中斷,後面的人收不到通知。正式實作應在呼叫外層包 try/catch。
現成方案。Node.js 內建的 EventEmitter 已完整實作這個模式,瀏覽器端則有 DOM 的 addEventListener/dispatchEvent。除非學習目的,否則不必自己刻。而手刻 Pub/Sub 最大的風險是可追蹤性下降——事件流一旦變得四通八達,除錯難度會遠高於直接呼叫。