Fork me on github

Js 设计常见设计模式

观察者模式

观察者模式主要特点就是 发布订阅 与 一对多, 也常被称为 发布订阅模式。

以下实现一个简单的主题功能

发布

首先需要定义一个主题类, 用于保存状态。并在状态发生变化之后发给所有的观察者

分解如下:

  1. 初始化状态、 初始化一个观察者数组
  2. getState 获取状态
  3. setState 修改当前状态, 并执行状态发布的方法
  4. notifyAllObservers 循环执行观察者数组中的更新方法
  5. attch 添加观察者
class Subject {
  constructor() {
    this.state = 0
    this.observes = []
  }

  getState() {
    return this.state
  }

  setState(state) {
    this.state = state
    this.notifyAllObservers()
  }

  notifyAllObservers() {
    this.observes.forEach(ob => {
      ob.update()
    })
  }

  attach(observe) {
    this.observes.push(observe)
  }
}

订阅

  1. 初始化当前订阅者基础信息、将主题绑定给当前订阅者、 主题订阅数组中添加当前订阅
  2. update 提供给主题状态发生改变时调用方法
class Observer {
  constructor(name, subject) {
    this.name = name
    this.subject = subject
    this.subject.attach(this)
  }

  update() {
    console.log(this.subject.state, `-----------${this.name}`);
  }
}

以上方法一个简单的发布订阅实现完毕, 它的一对多体现在使用过程中,

let theme = new Subject()
let o1 = new Observer('o1', theme)
let o2 = new Observer('o2', theme)
let o3 = new Observer('o3', theme)
let o4 = new Observer('o4', theme)

theme.setState('Rose Gold')
theme.setState('Rose Gold')
posted @ 2020-04-19 19:13  vanst  阅读(227)  评论(0)    收藏  举报