观察者模式

137 阅读1分钟

  • 被观察者,内部状态变化通知观察器
  • 观察者,通过被观察者对象方法挂载到被观察者上面
// 观察者模式
class Subject {
    constructor() {
        this.arr = [];
        this.state = 'pending';
    }
    setState(newState) {
        this.state = newState;
        this.arr.forEach(o => o.updated(this));
    };
    attach(o) {
        this.arr.push(o);
    }
}
class Observer {
    constructor(name) {
        this.name = name;
    }
    updated(s) {
        console.log(s.state, this.name);
    }
}

let s = new Subject('活动器');
let o1 = new Observer('观察者1');
let o2 = new Observer('观察者2');
s.attach(o1);
s.attach(o2);
s.setState('success');