一个主体有多个观察者,当主体的状态发生改变时,通知观察者。
代码示例:
class Subject { private state = 0; private observers: Observer[] = []; getState() { return this.state; } setState(newState: number) { this.state = newState; this.notify(newState); } attach(observer: Observer) { this.observers.push(observer); } private notify(state: number) { this.observers.forEach((observer) => { observer.update(state); }); } } class Observer { constructor(private name: string) {} update(state: number) { console.log(`${this.name}先生:${state}号客人的餐已经好了`); } } const observer1 = new Observer('小明'); const observer2 = new Observer('小张'); const subject = new Subject(); subject.attach(observer1); subject.attach(observer2); subject.setState(2);
UML类图: