美文网首页
2019-05-03

2019-05-03

作者: 小红帽哟 | 来源:发表于2019-05-03 16:45 被阅读0次

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

观察者模式

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

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

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;

}());

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

相关文章

网友评论

      本文标题:2019-05-03

      本文链接:https://www.haomeiwen.com/subject/ubkznqtx.html