Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

观察者模式 #21

Open
txw2018 opened this issue Oct 22, 2021 · 0 comments
Open

观察者模式 #21

txw2018 opened this issue Oct 22, 2021 · 0 comments

Comments

@txw2018
Copy link
Owner

txw2018 commented Oct 22, 2021

观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个目标对象,当这个目标对象的状态发生变化时,会通知所有观察者对象,使它们能够自动更新。 —— Graphic Design Patterns

在我们平时开发过程中,开发一个需求,产品经理把相关开发人员来到一个群,然后把相关需求通知到大家,然后相关人员接收到信息,进行开发,这就是类似一个观察者模式

// 定义发布者类
class Publisher {
  constructor() {
    this.observers = []
    console.log('Publisher created')
  }
  // 增加订阅者
  add(observer) {
    console.log('Publisher.add invoked')
    this.observers.push(observer)
  }
  // 移除订阅者
  remove(observer) {
    console.log('Publisher.remove invoked')
    this.observers.forEach((item, i) => {
      if (item === observer) {
        this.observers.splice(i, 1)
      }
    })
  }
  // 通知所有订阅者
  notify() {
    console.log('Publisher.notify invoked')
    this.observers.forEach((observer) => {
      observer.update(this)
    })
  }
}
// 定义订阅者类
class Observer {
    constructor() {
        console.log('Observer created')
    }

    update() {
        console.log('Observer.update invoked')
    }
}
const 产品经理 = new Publisher ()

const 前端 = new Observer ()

const 后端 = new Observer ()

const UI = new  Observer ()

产品经理.add(前端)
产品经理.add(后端)
产品经理.add(UI)
产品经理.notify()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant