觀察者模式
var Observer = (function () {
var _message = {};
return {
// 注冊消息
register: function (type, fn) {
// 傳入兩個參數(shù)差牛,一個是消息類型昔汉,另外一個是函數(shù)(該消息類型執(zhí)行的對應(yīng)的動作)
if (typeof _message[type] === 'undefined') {
// 如果消息隊列中沒有這個消息類型比勉,就在消息隊列中為這個消息類型創(chuàng)建一個函數(shù)
_message[type] = [fn];
} else {
// 如果存在了這個消息類型,則往該消息類型棧中推入這個函數(shù)
_message[type].push(fn);
}
},
// 發(fā)布消息
fire: function (type, args) {
if (!_message[type]) {
return;
}
// 定義消息信息
var events = {
type: type,
args: args || {},
};
for (var i = 0; i < _message[type].length; i++) {
// 依次執(zhí)行注冊的消息對應(yīng)的動作序列
_message[type][i].call(this, events);
}
},
// 取消訂閱
remove: function (type, fn) {
// 消息隊列存在
for (var i = _message[type].length - 1; i > 0 ; i--) {
// 如果改動作存在則在消息隊列中移除響應(yīng)的動作
_message[type][i] === fn && _message[type].splice(i, 1);
}
}
};
})();
實例
var Student = function (result) {
var that = this;
that.result = result;
// 回答問題
that.say = function () {
console.log(that.result);
};
};
Student.prototype.answer = function (question) {
Observer.register(question, this.say);
};
Student.prototype.sleep = function (question) {
console.log(this.result + ' ' + question + '已被注銷');
Observer.remove(question, this.say);
};
var Teacher = function () {};
Teacher.prototype.ask = function (question) {
console.log('問題是' + question);
Observer.fire(question);
};
// 模擬三位學(xué)生
var student1 = new Student('學(xué)生1回答了問題');
var student2 = new Student('學(xué)生2回答了問題');
var student3 = new Student('學(xué)生3回答了問題');
// 三位學(xué)生訂閱了老師的問題
student1.answer('什么是設(shè)計模式');
student2.answer('什么是設(shè)計模式');
student2.answer('什么是前端');
student2.answer('什么是js');
student3.answer('什么是js');
// 后來學(xué)生3睡著了
student3.sleep('什么是js');
var teacher = new Teacher();
teacher.ask('什么是設(shè)計模式');
teacher.ask('什么是前端');
teacher.ask('什么是js');
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者