class Subject{
constructor(){
this.state = 0
this.observers = []
}
getState(){
return this.state
}
setState(state){
this.state = state
this.notifyAllObservers()
}
notifyAllObservers(){
this.observers.forEach(item=>{
item.update()
})
}
attach(observer){
this.observers.push(observer)
}
}
class Observer{
constructor(name,subject){
this.name = name
this.subject = subject
this.subject.attach(this)
}
update(){
console.log(`${this.name}被触发了值为${this.subject.getState()}`);
}
}
const s = new Subject()
const o1= new Observer('o1',s)
s.setState(1)
场景
1.网页事件绑定
所有的事件监听都是观察者模式
2.Promise
先注册事件,当请求结束后Promise状态发生改变后再执行
3.vue和React组件生命周期触发
4.vue watch
设计模式验证
主题和观察者分离,不是主动触发而是被动监听,二者解耦。