观察者模式(2)--发布订阅模式

发布订阅模式和观察者模式的不同在于,增加了第三方即事件中心;目标对象状态的改变并直接通知观察者,而是通过第三方的事件中心来派发通知。

按照上一篇的观察者可以看着出来,当发布一个主题发布一个消息时,所有的观察者都能接收到,但现实的业务中 会存在按照一定的条件进行消息的推送,并不是所有的观察者都需要;


假如有这样一个 业务,是售楼部发布新房,根据买房者需求不同,进行相应的消息通知!


按照观察者进行编写 上代码

观察者
  class Sub{ //售楼部
    constructor(){
      this.obList=[]  //收集 买房者信息
    }
    addOb(obSever){ //添加
      this.obList.push(obSever)
    }
    // 通知每个观察者 并携带信息
    notify(dataInfo){
      this.obList.forEach(observer =>{
          observer.upData(dataInfo)
      })
    }
  }
//买房者
  class obServer{
    constructor(name){
      this.name=name
    }
    upData(data){
      console.log(`买房 ${this.name}接收到${data}`);
    }
  }
 
  let sub= new Sub()
  let ob1=new obServer('张三')
  let ob2=new obServer('李四')
 
  sub.addOb(ob1)  //售楼部添加 张三信息
  sub.addOb(ob2)  //售楼部添加 李四信息
 
  sub.notify('100平的毛培房')  //发布消息实现群体通知

实现发布订阅模式代码

    class Sub { //售楼部
      constructor(name, obServer) {
        this.name = name;
        this.obServer = obServer;
      }
      // 售楼部名称
      addTopic(topicName) {
        this.obServer.addTopic(topicName);
      }
      // 推送房型
      publish(topicName) {
        this.obServer.publish(topicName);
      }
    }
    //买房者
    class obServer {
      constructor(name,obServer) {
        this.name = name
        this.obServer = obServer
      }
      subscribe(topicName) {
        this.obServer.subscribeTopic(topicName, this);
      }
      upData(data) {
        console.log(`买房 ${this.name}接收到${data}`);
      }
    }

    class SubServer { //事件中心
      constructor() {
        this.topics = {};
      }
      //添加售楼部房屋分类
      addTopic(topicName) {
        this.topics[topicName] = [];
      }
      //买房者订阅 相应房屋分类
      subscribeTopic(topicName, sub) {
        if (this.topics[topicName]) {
          this.topics[topicName].push(sub);
        }
      }
      //平台通知某个房屋分类下所有买房者
      publish(topicName) {
        this.topics[topicName].forEach((item) => {
          item.upData(topicName);
        });
      }
    }
    let SubS = new SubServer()  //初始化事件中心
    let sub = new Sub('1号售楼部', SubS) //绑定售楼部
    sub.addTopic('88')        //售楼部 提供相应的房型88平
    sub.addTopic('100')       //售楼部 提供相应的房型100平

    let ob1 = new obServer('张三', SubS) //
    let ob2 = new obServer('李四', SubS) //

    ob1.subscribe("88");  //张三关注了88平
    ob1.subscribe("100"); //张三关注了100平
    ob2.subscribe("88");  //李四关注了88平


    sub.publish('88')     //售楼部推出88平房子
    sub.publish('100')    //售楼部推出100平房子

两种实现上很相似但又有所区别,发布订阅模式可能就更加灵活比较符合一些业务的实现;事件中心是将之前放在主题的部分逻辑进行解耦,在通过对象的形式实现的,定类推送消息不再是全部推送;

上叙都是模式的简单实现,里面还存在取消订阅,订阅全部....,可以根据实际的业务进行实现

posted @ 2022-07-25 15:37  xiao旭  阅读(57)  评论(0编辑  收藏  举报