观察者模式(Observer Pattern)
|
1 2 3 |
定义:当一个对象被修改时,则会自动通知它的依赖对象。 目的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 场景:一个对象(目标对象)的状态发生改变,所有的依赖对象(观察者对象)都将得到通知,进行广播通知。 |
|
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
class Subject { #state = 0 #observers = new Set() getState() { return this.#state } setState(state) { if (Object.is(this.#state, state)) { return } const previousState = this.#state this.#state = state this.notifyAllObservers({ previousState, currentState: state }) } attach(observer) { if (typeof observer?.update !== 'function') { throw new TypeError('观察者必须提供 update() 方法') } this.#observers.add(observer) // 返回取消订阅函数 return () => { this.detach(observer) } } detach(observer) { return this.#observers.delete(observer) } notifyAllObservers(change) { // 使用快照,避免通知期间修改集合影响当前遍历 const observers = [...this.#observers] for (const observer of observers) { observer.update(this, change) } } } // 观察者: class Observer { constructor(name, subject) { this.name = name this.unsubscribe = subject.attach(this) } update(subject, change) { console.log( `${this.name}:`, change.previousState, '→', change.currentState ) console.log('当前状态:', subject.getState()) } dispose() { this.unsubscribe() } } // 使用: const subject = new Subject() const observer1 = new Observer('observer 1', subject) const observer2 = new Observer('observer 2', subject) subject.setState('hahaha') |

