通用设计模式之观察者模式(发布-订阅者模式)

通常又被称为 发布-订阅者模式 (Publisher/Subscribers):它定义了对象和对象间的一种依赖关系,只要当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新,解决了主体对象与观察者之间功能的耦合。

生活中观察者模式也是非常常见的,比如订阅公众号,订阅报纸,订阅各种媒体等:当被订阅的主体的状态发生改变,比如有新的消息,就通知订阅者。

以下是观察者模式在JS中的简单实现:

class Publisher{
  _state = 0;
  subscribers = []

  get state(){
    return this._state
  }
  set state(value){
    this._state = value
    this.notify(value)
  }
  notify(value){
    this.subscribers.forEach(subscriber => subscriber.update(value))
  }
  collect(subscriber){
    this.subscribers.push(subscriber)
  }
}
let subId = 1
class Subscriber{
  publisher = null;
  id = subId++;
  subscribe(publisher){
    this.publisher = publisher
    publisher.collect(this)
  }
  update(value){
    console.log(`我是${this.id}号订阅者,收到发布者信息:${value}`);
  }
}
let publisher = new Publisher()
let subscriber1 = new Subscriber()
let subscriber2 = new Subscriber()
subscriber1.subscribe(publisher)
subscriber2.subscribe(publisher)
publisher.state = 2

观察者的使用场合就是:当一个对象的改变需要同时改变其它对象,并且它不知道具体有多少对象需要改变的时候,就应该考虑使用观察者模式。

示例:各种原生事件,自定义事件。vue源码。

猜你喜欢

转载自www.cnblogs.com/wtsx-2019/p/12615127.html