# 观察者模式
当一个对象发生变化时,其他依赖该对象的对象都会受到通知。
定义一个被观察者
function Subject(){
this.count = 0
this.observers = [] // 所有观察者
this.add = function(){
this.count++
// 当数据变化之后通知所有观察者
this.notifyAll()
}
this.append = function(observer){ // 添加新的观察者
this.observers.push(observer)
}
this.notifyAll = function(){ // 通知所有观察者
this.observers.forEach(observer => {
observer.messaged(this.count)
})
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
初始化一个被观察者,接下来定义几个观察者,并使其观察被观察者
var subject = new Subject()
var observer1 = {
name: 'observer1',
messaged: function(count){
console.log('观察者:'+this.name+' 数据变化:'+count)
}
}
var observer2 = {
name: 'observer2',
messaged: function(count){
console.log('观察者:'+this.name+' 数据变化:'+count)
}
}
subject.append(observer1)
subject.append(observer2)
subject.add()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16