概述
訂閱發佈者模式如果不進行細膩度的劃分也有稱之爲消息通信模式、中介模式或者觀察者模式。故名思意需要有訂閱和發佈,當訂閱了某一個事件後,通過發佈操作可以通知到所有的訂閱者執行相關操作。
實現
要完成訂閱發佈者模式,首先需要一箇中介或者說叫做觀察者:
var Observe = {}; //這是一個觀察者,所有的操作都由它來執行,可以將其定義爲一個object
其次就是需要一個保存訂閱消息的容器:
//由於需要一個內部私有容器來保存消息,所以需要將其改變下結構
var Observe = (function () {
var _message = {}; //用於保存訂閱消息的容器
}());
最後就是需要有的操作,包括但不限於訂閱操作和發佈操作:
var Observe = (function () {
var _message = {};
return {
register: function () {}, //訂閱操作
publish: function () {} //發佈操作
}
}());
然後完善一下訂閱和發佈的具體操作了:
var Observe = (function () {
var _message = {};
return {
register: function (type, fn) { //消息類型type,對應操作fn
if (_message[type]) { //消息容器中有對應的type,直接往隊列中添加
_message[type].push(fn);
} else { //消息容器中沒有對應的type,則先創建隊列,再添加
_message[type] = [];
_message[type][0] = fn;
}
},
publish: function (type) {
if (_message[type]) {
_message[type].forEach(item => {
typeof item === 'function' && item();
});
}
}
}
}());
到這裏,一個簡單的訂閱發佈者模式構就建好了。
測試
Observe.register("SayHi", function () { console.log('Hi, I am the first.'); });
Observe.register("SayHi", function () { console.log('Hi, I am the second.'); });
Observe.register("SayHi", function () { console.log('Hi, I am the three.'); });
Observe.register("SayHello", function () { console.log('Hello, I am the four.'); });
Observe.publish("SayHi");
//輸出爲
//Hi, I am the first.
//Hi, I am the second.
//Hi, I am the three.