//定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变的时候,所有依赖于他的对象都得到通知并自动刷新
// 观察者放在闭包,页面加载就立即执行
var Observer = (function(){
//消息队列私有
var _message = {};
return {
//注册信息
regist:function(type,fn){
//一种类型对应多个模块注册的执行函数
if(typeof _message[type] === "undefined"){
_message[type] = [fn];
}else{
_message[type].push(fn);
}
},
//发布信息
fire:function(type,args){
if(!_message[type]){
return;
}
var events = {
type:type,
args:args || {}
};
var i = 0;
var len = _message[type].length;
for(; i<len;i++){
//依次执行注册的消息对应的执行函数
_message[type][i].call(this, event);
}
},
//移除信息
remove:function(type,fn){
if(_message[type] instanceof Array){
var i = _message[type].length - 1;
for(; i>0;i--){
_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.choose = function(course){
Observer.regist(course,this.say);
}
Student.prototype.unchoose = function(course){
console.log(this.result + " " + course + "已经退选");
Observer.remove(course,this.say);
}
var Teacher = function(){}
Teacher.prototype.ask = function(question){
console.log("谁选了:" + question);
Observer.fire(question);
}
var student1 = new Student("学生1选修");
var student2 = new Student("学生2选修");
var student3 = new Student("学生3选修");
student1.choose("数学");
student1.choose("历史");
student2.choose("计算机");
student3.choose("数学");
student3.choose("历史");
student3.unchoose("历史");
var teacher = new Teacher();
teacher.ask("数学");
teacher.ask("历史");
设计模式之观察者模式
最新推荐文章于 2024-07-20 17:22:42 发布