发布订阅模式

目前非常流行的 vue 的底层,其实用的就是发布订阅模式。要学习vue的原理的话,很有必要先学习一下这个设计模式。

发布订阅模式

在观察者模式中一般有两个对象发布者和订阅者,订阅者从发布者那里订阅消息,发布者发布消息通知所有订阅消息的对象。当订阅者订阅发布者的时候,发布者会把订阅者添加到自己的订阅者列表中。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

function Publisher(){
this.observers = [];
}

/**
发布者添加订阅对象
**/
Publisher.prototype.add = function(observer){
this.observers.push(observer);
}


/**
发布者通知订阅者
**/
Publisher.prototype.notify = function(context){
this.observers.forEach((observer)=>{
observer.update(context)
});
}


function Observer(){

}

Observer.prototype.update=function(context){
console.log(context)
}

/**
订阅发布者
**/
Observer.prototype.subscribe=function(publisher){
publisher.add(this)
}

var publisher = new Publisher();
var observer = new Observer();

observer.subscribe(publisher);
publisher.notify('事件发布');