客戶端應用隨著複雜度增長,組件間通訊不可避免。理解觀察者模式與中介者模式的區別與適用場景,是設計可維護訊息架構的關鍵。
class Subject {
constructor() { this.observers = []; }
subscribe(fn) { this.observers.push(fn); }
unsubscribe(fn) { this.observers = this.observers.filter(f => f !== fn); }
notify(data) { this.observers.forEach(fn => fn(data)); }
}
const button = new Subject();
button.subscribe(() => console.log('Clicked!'));
button.notify({x: 100, y: 200}); // 直接耦合:觀察者必須持有 Subject 參考
class Mediator {
constructor() { this.channels = {}; }
subscribe(channel, fn) {
(this.channels[channel] ||= []).push(fn);
}
publish(channel, data) {
(this.channels[channel] || []).forEach(fn => fn(data));
}
unsubscribe(channel, fn) {
this.channels[channel] = (this.channels[channel] || []).filter(f => f !== fn);
}
}
const bus = new Mediator();
// 發布者:不知誰在聽
class FatherTime {
constructor(mediator) { this.mediator = mediator; }
wakeyWakey() {
this.mediator.publish('alarm.clock', {time: '06:00', snooze: false});
}
}
// 訂閱者:不知誰發布
class Developer {
constructor(mediator) {
this.mediator = mediator;
mediator.subscribe('alarm.clock', this.pleaseGodNo.bind(this));
}
pleaseGodNo(data) {
alert(`ZOMG, it's ${data.time}. Make it stop.`);
}
}
new FatherTime(bus).wakeyWakey(); // Developer 收到通知
| 場景 | 推薦模式 | 理由 |
|---|---|---|
| View 直接操作 Model、需雙向同步 | 觀察者 | View 需調用 Model 方法,自然持有引用 |
| 多個 View 回應同一 Model 變更 | 中介者 | Model 不應知 View 存在,避免循環依賴 |
| 跨功能模組通訊(認證、通知、分析) | 中介者 | 模組獨立部署、版本迭代,僅共享事件契約 |
| 父子組件通訊 | 觀察者 / Props | 父組件天然持有子組件引用 |
| 兄弟組件通訊 | 中介者 | 無直接引用關係 |
保持組件內部使用觀察者(如 Backbone Events),僅在需要跨模組時橋接至中介者:
class UserModel extends Backbone.Model {
initialize() {
// 本地事件:View 直接監聽
this.on('change:name', this.onNameChange, this);
// 橋接至全域總線:其他模組監聽
this.on('change:name', (model, name) => {
bus.publish('user:nameChanged', {id: this.id, name});
});
}
}
優勢:
mitt / event-emitter;React: Context + useReducer / zustand / jotai觀察者與中介者非對立,而是互補。優秀的客戶端架構:組件內部用觀察者(高效、直觀),跨組件/跨模組用中介者(解耦、擴展),並在需要時橋接兩者。明確訂定事件契約(名稱、載荷結構、語義),配合 TypeScript 型別檢查,能構建出清晰、可演進的訊息驅動架構。