设计模式(八)-发布订阅模式

2021-02-08  本文已影响0人  仔崽06

发布订阅模式

在软件架构中,发布订阅是一种消息范式,消息的发送者(发布者)不会将消息发送给特定的接收者(订阅者),发布者和订阅者不知道彼此的存在,通过第三方代理(proxy),接收订阅者的消息订阅,发布者发生改变,自动通知所对应的订阅者.

//中介  订阅 发布
class Agent{
   constructor(){
       this._events={}
   }
   //订阅事件类型
   subscribe(type,listener){
       let listeners=this._events[type]
       if(listeners){
           listeners.push(listener)
       }else{
           this._events[type]=Array.of(listener)
       }
   }
   //发布
   publish(type){
       let listeners=this._events[type]
       let arg=Array.prototype.slice.call(arguments,1)
       if(listeners){
           listeners.forEach(listener=>{
               listener(...arg)
           })
       }
   }
}

//租客
class Tenant{
    constructor(name){
        this.name=name
    }
    //租房  订阅消息
    rent(agent){
        agent.subscribe('house',(area,money)=>{
             console.log(`${this.name}:看到新房源${area}平米${money}钱`)
        })
    }
}

//房东
class LandLord{
    constructor(name){
        this.name=name
    }
    //发布出租
    lend(agenr,area,money){
        agenr.publish('house',area,money)
    }
}

let agent=new Agent();
let t1= new Tenant('张三')
let t2= new Tenant('李四')
t1.rent(agent)
t2.rent(agent)
let landLord=new LandLord('房东1')
landLord.lend(agent,60,4800)
//张三:看到新房源60平米4800钱
//李四:看到新房源60平米4800钱
区别
观察者模式:被观察者和观察者之间是耦合的,被观察者更新状态update动作是由被观察者来调用的.
发布订阅模式:发布订阅模式被观察者与观察者之间是解耦的,彼此都不知道存在,多了一个发布通道,发布通道像发布者接收发布,像订阅者接收订阅,发布者改变直接通过发布通道(Proxy)通知订阅者.
上一篇下一篇

猜你喜欢

热点阅读