什麼是中介者模式?
中介者模式(Mediator)是用來降低多個對象和類之間的通信複雜性。這種模式提供一箇中介類,該類通常處理不同類的通信,並支持鬆耦合,使代碼易於維護。中介者模式屬於行爲模式。
實現
var mediator = (function () {
var topics = {}
// 訂閱一個 topic,提供一個回調函數,一旦 topic 被廣播就執行該回調
var subscribe = function(topic, fn) {
if (!topics[topic]) {
topics[topic] = []
}
topics[topic].push({
context: this,
callback: fn
})
return this
}
// 發佈/廣播事件到程序的剩餘部分
var publish = function(topic) {
var args
if (!topics[topic]) {
return false
}
args = Array.prototype.slice.call(arguments, 1)
for (var i = 0, l = topics[topic].length; i < l; i++) {
var subscription = topics[topic][i]
subscription.callback.apply(subscription.context, args)
}
return this
}
return {
publish: publish,
subscribe: subscribe
}
})()
使用
我們舉個生活中常見的例子——羣聊。
// 小A加入了前端羣,如果羣裏有人說話,自己就會收到消息
mediator.subscribe('fe-group', function(data) {
console.log(data)
})
// 小B也加入了前端羣,如果羣裏有人說話,自己就會收到消息
mediator.subscribe('fe-group', function(data) {
console.log(data)
})
// 這個時候小B在羣裏給小A發送了一條信息
// 在羣裏的人都會收到這條信息
// 打印兩次 {message: 'hello A', from: 'B', to: 'A'}
mediator.publish('fe-group', {message: 'hello A', from: 'B', to: 'A'})
這個例子中,羣就是一箇中介者 Mediator,而小A、小B是 Collegue,他們都是通過羣來通信的。
試想如果沒有羣這個中介者,每個人就通過私聊來互相溝通,那麼就需要不斷切換聊天窗口,很麻煩。而且這樣會形成一個網狀的結構。而有了中介者,大家的溝通就會變得很容易,都在羣裏發送和查看消息。這樣網狀結構就會變成星狀結構。