设计模式-发布订阅模式

描述

发布订阅模式

我去书店买 《水浒传》,如果没有,我会告诉店员
如果 书来了,请通知我。店员则是我们的构造函数,负责监听事件以及通知我们
店员会在自己的记事本上写下 ,因为店员要通知的可能不止一个人
《水浒传》:[handlerA,handlerB]
分析构造函
属性:消息队列
{
click:[fn1,fn2],
abc:[fn1,fn2,fn3],
'水浒传':[fn1,fn2]
}
方法1:向消息队列中添加内容
方法2:向消息队列中添加一条信息
方法3:触发消息队列里面的内容

代码实现

// 发布订阅模式
/*
  我去书店买 《水浒传》,如果没有,我会告诉店员
  如果 书来了,请通知我
  店员会在自己的记事本上写下  ,因为店员要通知的可能不止一个人
  《水浒传》:[handlerA,handlerB]
    分析构造函数:
      属性:消息队列 
          {
            click:[fn1,fn2],
            abc:[fn1,fn2,fn3],
            '水浒传':[fn1,fn2]
          }
      方法1:向消息队列中添加内容
      方法2:向消息队列中添加一条信息
      方法3:触发消息队列里面的内容

*/
class Observer {
  constructor() {
    this.messageList = {}   // 消息队列
  }
  // 1. 向消息队列里面添加内容
  on (type, fn) {
    if (!this.messageList[type]) {
      this.messageList[type] = []
    }
    this.messageList[type].push(fn)
  }
  // 2. 移除消息队列里的内容

  off (type, fn) {
    if (!fn) {
      delete this.messageList[type]
      return
    }
    if (!this.messageList[type]) return
    this.messageList[type] = this.messageList[type].filter(item => item !== fn)
  }
  // 出发消息队列里面的事件
  emit (type) {
    if (!this.messageList[type]) {
      console.log(`《${type}》此书已不售卖`)
      return
    }
    this.messageList[type].forEach(item => {
      item()
    })
  }
}
const person1 = new Observer()
const person2 = new Observer()
// 让person1帮我们关注某个行为
// 店员分别添加了A、B、C
person1.on('水浒传', handlerA)
person1.on('水浒传', handlerB)
person1.on('水浒传', handlerC)
// A突然告诉店员,不需要了,则移除A
person1.off('水浒传', handlerA)
person1.emit('水浒传')



// ABC分别告诉店员2,它们需要小黄书,来了通知他们
person2.on('小黄书', handlerA)
person2.on('小黄书', handlerB)
person2.on('小黄书', handlerC)
// 打印部突然通知,小黄书被国家禁了,不再印,店员2则删除这条相关信息
person2.off('小黄书')
person2.emit('小黄书')




function handlerA () {
  console.log('当前通知了A')
}
function handlerB () {
  console.log('当前通知了B')
}
function handlerC () {
  console.log('当前通知了C')
}
function handlerD () {
  console.log('当前通知了D')
}
function handlerE () {
  console.log('当前通知了E')
}
posted @ 2023-03-15 14:39  含若飞  阅读(20)  评论(0编辑  收藏  举报