两者区别简述:
1. 发布订阅模式是最常用的一种观察者模式的实现,并且从解耦和重用角度来看,更优于典型的观察者模式
2. 订阅者有调度中心
观察者模式:
![](https://images2018.cnblogs.com/blog/724609/201808/724609-20180813134343512-248375043.png)
发布订阅模式:
代码实现上的区别:
// 观察任意数组的push操作
let array = { watch(target, callback) { if (target instanceof Array) { let push = target.push; let _this = this; Object.defineProperty(target, "push", { writable: true, enumerable: false, configurable: true, value: function(exponent) { callback.apply(_this, arguments); push.apply(target, arguments); } }) } } } var arr = [1, 2, 3, 4, 5];
array.watch(arr, function(value) { console.log('push :', [].slice.call(arguments)) }); arr.push(6, 7); console.log(arr);
var arr1 = [8, 9]; array.watch(arr1, function(value) { console.log('push :', [].slice.call(arguments)) }); arr1.push(10, 11); console.log(arr1);
// 订阅者与发布 class Subscriber { constructor() { this.list = []; } // 订阅 subscribe(name, callback) { if (typeof callback !== "function") { throw new Error('subscribe method param2:callback is not a function'); return false; } if (this.list[name] && this.list[name] instanceof Array) { this.list[name].push(callback); } else { this.list[name] = [callback]; } } // 发布 release(name, data) { if (typeof this.list[name] === "undefined") { throw new Error(name + ' event is undefined!'); } else { this.list[name].forEach((callback) => { typeof callback === "function" && callback.call(this, data); }); } } } // 实例化线人 let my = new Subscriber(); my.subscribe('eventName', (data) => { console.log(data); }); my.release('eventName','doing something!');