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

196 阅读1分钟

发布订阅模式

class EventBus {
  constructor() {
    this.arr = []
  }
  on(fn) {
    this.arr.push(fn)
  }
  emit() {
    this.arr.forEach(f=>f())
  }
}
let eventBus = new EventBus()
eventBus.on(()=>{
  console.log(1);
})
eventBus.on(()=>{
  console.log(2);
})
eventBus.emit()

观察者模式

// 被观察者
class Patient {
  constructor(name) {
    this.name = name
    this.attacher = []
  }
  attach(d) {
    this.attacher.push(d)
  }
  call(){
    this.attacher.forEach(d=>d.doSomething(this))
  }
}

// 观察者
class Doctor {
  constructor(name) {
    this.name = name
  }
  doSomething(p){
    console.log(this.name + ':' + p.name + ' is call me');
  }
}

let p1 = new Patient('p1')
let p2 = new Patient('p2')
let d1 = new Doctor('d1')
let d2 = new Doctor('d2')
p1.attach(d1)
p1.attach(d2)
p1.call()
p2.call()

发布订阅与观察者模式的区别

发布订阅模式是任意绑定和触发的,不存在关联关系;而观察者模式存在观察者和被观察者,并且需要建立两者之间的关联关系。在前端,这两种模式都广泛使用。比如:在vue中,组件之间的通信onon和emit就是发布订阅模式;而数据的依赖收集则采用的是观察者模式。