前端需要了解的设计模式

146 阅读1分钟

观察者模式

观察者模式,也叫发布订阅模式,监听者模式。其概念就是一个或多个对象依赖于某一个对象,当这个对象的状态发生改变时,所有依赖于它的对象都得到状态改变的通知。

  • 示例:
/**
 * @description: 观察者模式
 */
class Observe {
  constructor(name, fn = () => { }) {
    this.name = name
    this.fn = fn
  }
}

class Subject {
  constructor(state) {
    this.state = state
    this.observes = []
  }
  getState() {
    return this.state
  }
  setState(newState) {
    if (this.state === newState) return
    this.state = newState
    this.notifyAllObservers()
  }
  notifyAllObservers() {
    this.observes.map(item => item.fn(this.state))
  }
  listen(observe) {
    if (!this.observes.includes(observe)) {
      this.observes.push(observe)
    }
  }
  unlisten(observe) {
    const index = this.observes.indexOf(observe)
    if (index > -1) {
      this.observes.splice(index, 1)
    }
  }
}
  • 测试
const o1 = new Observe('小夫', (state) => { console.log(`${state} ==> 小夫 --> 打篮球`)})
const o2 = new Observe('胖虎', (state) => { console.log(`${state} ==> 胖虎 --> 睡大觉`) })

const s1 = new Subject('学习')

s1.listen(o1)
s1.listen(o2)

s1.setState('玩') 
// 玩 ==> 小夫 --> 打篮球
// 玩 ==> 胖虎 --> 睡大觉

s1.unlisten(o1)

s1.setState('学习')
// 学习 ==> 胖虎 --> 睡大觉
  • 应用场景
  1. addEventLisener 绑定事件
  2. Vuex 监听事件变化
  3. node 自定义事件