观察者模式
观察者
class Observer {
constructor (name, action = () => {}) {
this.name = name
this.action = action
}
}
被观察者
- observers 数组用来保存所有观察者
- 当state 变化时,观察者将作出响应
class Subject {
constructor (state) {
this.state = state
this.observers = []
}
setState (val) {
this.state = val
this.observers.forEach(item => {
item.action(this.state)
})
}
addObserver (val) {
this.observers = this.observers.filter(item => item !== val)
this.observers.push(val)
}
delObserver (val) {
this.observers = this.observers.filter(item => item !== val)
}
}
示例
- Jack 为被观察者,observer1, observer2 为jack 的两个观察者
- 当 Jack 的状态发生变化时,observer1 和 observer2 就会作出响应
const observer1 = new Observer('observer1', (state) => { console.log('observer1: state ->', state) })
const observer2 = new Observer('observer2', (state) => { console.log('observer2: state ->', state) })
const jack = new Subject('study')
jack.addObserver(observer1)
jack.addObserver(observer2)
jack.setState('play')