觀察者模式和訂閱發(fā)布模式
觀察者模式
相當(dāng)于租客和房東直接聯(lián)系
//每個(gè)觀察者有個(gè)更新函數(shù)
function observer() {
this.update=function (args) {
}
}
function observerlist(){
this.observerlist=[];
}
/*
* 添加觀察者* param obj? 一個(gè)observe對(duì)象* */
observerlist.prototype.add=function (obj) {
if (obj){
this.observerlist.push(obj)
}
};
/*
* 得到觀察者的數(shù)量* */
observerlist.prototype.len=function () {
return this.observerlist.length;
};
/*
* 刪除觀察者* param obj 一個(gè)觀察者對(duì)象* */
observerlist.prototype.remove=function (obj) {
let index=this.observerlist.indexOf(obj);
? ? this.observerlist.splice(index,1);
};
/*
* 得到具體觀察者* param index 觀察者的下標(biāo)* */
observerlist.prototype.get=function(index){
return this.observerlist[index];
};
function subject() {
this.observes=new observerlist();
}
/*
* 遍歷所有觀察者對(duì)象晒杈,調(diào)動(dòng)他們的update函數(shù)* */
subject.prototype.all=function(args){
let len=this.observes.len();
? ? for(let i=0;i
this.observes.get(i).update(args);
? ? }
};
/*
* 添加觀察者* */
subject.prototype.add=function(obj){
this.observes.add(obj);
};
/*
* 刪除觀察者* */
subject.prototype.remove=function(obj){
this.observes.remove(obj);
};
subject--------------調(diào)用------------------>observer
observer------------注冊(cè)------------------>subject
訂閱發(fā)布模式
相當(dāng)于房東和租客之間通過中介間接聯(lián)系,可以解耦合
let pubsub=(function () {
let obj={};
? ? let topics=[];
? ? let userid=-1;
? ? /*
? ? * 發(fā)布消息通知所有訂閱者,調(diào)用回調(diào)函數(shù)* */
? ? obj.publish=function (topic,args) {
if(!topics[topic]){
return false;
? ? ? ? }
let temp=topics[topic];
? ? ? ? let len=topics[topic].length;
? ? ? ? for(let i=0;i
temp[i].fn(args);
? ? ? ? }
};
? ? /*
? ? * 訂閱? ? * 添加訂閱話題和綁定回調(diào)事件* */
? ? obj.subscibe=function (topic,fn) {
if(!topics[topic]){
topics[topic]=[]
}
var index=(++userid).toString();
? ? ? ? topics[topic].push({
index,
? ? ? ? ? ? fn
? ? ? ? })
};
? ? /*
? ? * 取消訂閱? ? * 刪除話題* */
? ? obj.unsubscribe=function(k){
for(let topic in topics){
if(topic){
for(let i=topic.length-1;i>=0;i--){
if(topic[i].index===k){
topics[topic].splice(k,1);
? ? ? ? ? ? ? ? ? ? }
}
}
}
};
? ? return obj;
}());
訂閱者--------------------發(fā)布---------------------->調(diào)度中心---------------------------通知---------------------->訂閱者