let Observer = (() => {
var _messages = {};
return {
regist: (type,fn) => {
if(typeof _messages[type] === 'undefined'){
_messages[type] = [];
_messages[type].push(fn);
}else{
_messages[type].push(fn);
}
},
fire: (type,args) => {
if(!type){return;}
let events ={
type: type,
args: args || {}
},
i = 0,
len = _messages[type].length;
for(; i < len; i++){
_messages[type][i].call(this, events);
};
},
remove: (type,fn) => {
if(_messages[type] instanceof Array){
let i = _messages[type].length - 1;
for(; i >= 0; i--){
_messages[type][i] === fn && _messages[type].splice(i, 1);
_messages[type].length === 0 && delete _messages[type];
}
}
}
}
})();
class Student {
constructor(result){
this.result = result;
this.say = this.say.bind(this);
this.answer = this.answer.bind(this);
}
say(){
console.log(this.result);
}
answer(question){
Observer.regist(question, this.say);
}
sleep(question){
console.log(this.result+" "+question +" "+ '已被注销');
Observer.remove(question ,this.say);
}
}
class Teacher{
ask(question){
console.log('问题是:'+question);
Observer.fire(question);
}
}
let teacher = new Teacher();
let student1 = new Student('第1个学生回答问题'),
student2 = new Student('第2个学生回答问题'),
student3 = new Student('第3个学生回答问题');
student1.answer('什么是设计模式');
student1.answer('什么是观察者模式');
student2.answer('什么是设计者模式');
student2.answer('什么是设计者模式');
student3.answer('简述观察者模式');
student3.sleep('简述观察者模式');
teacher.ask('什么是设计模式');
console