fe ? not exsit ?

observer && publish-subscribe

设计模式种的经典模式,仅仅是学习记录。观察者宏观来讲没什么大的区别,依照软件工程的角度拆分的耦合度上来分析,调度中心分析是有区别的。不用太钻牛角尖,看具体场合使用把。

observer

obverList

观察者和订阅者相耦合,两者相互反馈,你订阅通知我,我发布通知你。举个生活的例子就是两个人光明磊落看互相不爽就对骂。

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
44
45
46
// 抽象一个observerList 来存储订阅
class ObserverList {
constructor() {
this.observerList = [];
}
add (action) {
action && this.observerList.push(action);
}
delete (action) {
this.observerList.forEach( (item, index) => {
if (item == action) {
this.splice(index, 1);
}
})
}
get (index) {
return this.observerList(index) ? this.observerList(index) : -1;
}
count () {
return this.observerList.length;
}
}

class Subject {
constructor() {
this.obser = new ObsercerList();
}
subscribe(val) {
this.obser.add(val);
}
unsubscribe(val) {
this.obser.delete(val);
}
notify(...arg) {
let count = this.obser.length, i = -1;
while(++i < count) {
this.obser.get(i).update(...arg);
}
}
}

class Observer {
update () {
console.log(' i am update');
}
}

publish && subscribe

pubsub

观察者和订阅者相解耦,两者通过一个调度中心反馈,你订阅到调度中心,它通知我,我发布到调度中心,它通知你。举个例子古时候打仗靠一个传令官通信。

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
class Pubsub {
constructor () {
this.subscribeList = {};
}

subscribe (type, func) {
if (!this.subscribeList[type]) {
this.subscribeList[type] = [];
}
this.subscribeList[type].push( { fun: func } );
}

unsubscibe (action) {
for ( var i in this.subscribeList) {
i.forEach( (item, index) => {
if ( item.fun == action ) {
i.splice(index, 1);
}
})
}
}

publish (type, ...arg) {
if (this.subscribeList[type]) {
this.subscribeList[type].forEach( item => {
item.fun(...arg);
})
}
}
}

总结

  • 区别最大的就是调度中心不同。
  • 不必要纠结名称可都称之为观察者模式。
  • 应用
    1. 鉴权在subscribe中做出逻辑限制
    2. 可以通过count和数组的长度来灰度。
    3. notify或称之为publish可以去抖操作进行。
    4. 浏览器事件等等。