1、观察者模式区分:观察者 & 观察目标,这里首先需要创建一个观察目标的集合。
class Wacther { constructor () { this.observers = []; } }
2、当观察目标集合创建好后,这里面 add 方法是为了添加观察目标的。
class Wacther { constructor () { this.observers = []; } add (obj) { this.observers.push(obj); } notify(...args) { this.observers.forEach(itemWatcher => itemWatcher.update(...args)); } } class Observer { update (...args) { console.log(...args); } }
3、测试使用: 让两个观察者对象同时监听某一个主题对象,这个主题对象的状态发生改变时就会通知所有观察着对象。
const a = new Observer(); const b = new Observer(); const watcher = new Wacther(); watcher.add(a); watcher.add(b); watcher.notify(‘I fired `SMS` event‘);
4、发布-订阅模式是面向调度中心编程的,而观察者模式则是面向目标和观察者编程的。前者用于解耦发布者和订阅者,后者用于耦合目标和观察者。
观察者模式如图:
发布订阅模式,发布者和订阅者不知道对方的存在。需要一个第三方组件,叫做信息中介,它将订阅者和发布者串联起来,它过滤和分配所有输入的消息。换句话说,发布-订阅模式用来处理不同系统组件的信息交流,即使这些组件不知道对方的存在。如图:
原文:https://www.cnblogs.com/JockerM/p/12056079.html