2019-05-03

观察者模式和订阅发布模式


观察者模式

相当于租客和房东直接联系

//每个观察者有个更新函数

function observer() {

this.update=function (args) {

}

}

function observerlist(){

this.observerlist=[];

}

/*

* 添加观察者* param obj  一个observe对象* */

observerlist.prototype.add=function (obj) {

if (obj){

this.observerlist.push(obj)

}

};

/*

* 得到观察者的数量* */

observerlist.prototype.len=function () {

return this.observerlist.length;

};

/*

* 删除观察者* param obj 一个观察者对象* */

observerlist.prototype.remove=function (obj) {

let index=this.observerlist.indexOf(obj);

    this.observerlist.splice(index,1);

};

/*

* 得到具体观察者* param index 观察者的下标* */

observerlist.prototype.get=function(index){

return this.observerlist[index];

};

function subject() {

this.observes=new observerlist();

}

/*

* 遍历所有观察者对象,调动他们的update函数* */

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--------------调用------------------>observer

observer------------注册------------------>subject



订阅发布模式

相当于房东和租客之间通过中介间接联系,可以解耦合

let pubsub=(function () {

let obj={};

    let topics=[];

    let userid=-1;

    /*

    * 发布消息通知所有订阅者,调用回调函数* */

    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);

        }

};

    /*

    * 订阅    * 添加订阅话题和绑定回调事件* */

    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;

}());


订阅者--------------------发布---------------------->调度中心---------------------------通知---------------------->订阅者

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容