关于javascript:观察者模式

观察者模式(Observer)

定义:属于行为型模式的一种,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变动时,会告诉所有的观察者对象,使他们可能自动更新本人。

实现

  <span id="num">1</span>
  <button onclick="numAdd()">+</button>
    var num = document.getElementById('num')
    function numAdd() {
      notice.setState(Math.floor(Math.random() * 10))
      num.innerText = notice.state + Math.floor(Math.random() * 10)
    }
    function Theme() {
      this.observers = []
      this.state = 0
      this.setState = function (newVal) {
        this.state = newVal
        this.notifyAllObservers()
      }
      this.attach = function (observer) {
        this.observers.push(observer)
      }
      this.notifyAllObservers = function () {
        this.observers.forEach((item) => item.updated(this.state))
      }
    }
    function Observer(name) {
      this.name = name
      this.updated = function (e) {
        console.log(`${this.name}接管到了新音讯`, e)
      }
    }
    var notice = new Theme()
    var observer1 = new Observer('观察者1')
    var observer2 = new Observer('观察者2')
    notice.attach(observer1)
    notice.attach(observer2)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理