Zachary W. Huang

Home Projects Blog Guides Resume

Observer

Idea: keep track of an object’s dependents so that any update to that object can be propagated to its observers automatically (aka pub/sub).

class Subject {
  state: any;
  observers: Record<string, Observer> = {};

  constructor(state: any) {
    this.state = state;
  }

  addObserver(name: string, observer: Observer) {
    this.observers[name] = observer;
  }

  removeObserver(name: string) {
    delete this.observers[name];
  }

  notify() {
    for (let o of Object.values(this.observers)) {
      o.update(this.state);
    }
  }
}

class Observer {
  state: any = null;

  constructor(state: any) {
    this.state = state;
  }

  update(state: any) {
    this.state = state;
  }

  doThing() {
    console.log(this.state);
  }
}

function main() {
  const subject = new Subject("A");
  const observer1 = new Observer("B");
  subject.addObserver("1", observer1);
  const observer2 = new Observer("C");
  subject.addObserver("2", observer2);

  observer1.doThing(); // "B"
  observer2.doThing(); // "C"
  subject.notify();
  observer1.doThing(); // "A"
  observer2.doThing(); // "A"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024