Observer

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests
S A D N C G S s u t e o o e e u b t t t n t t b j a a i c S S j e c c f r t t e c h h y e a a c t ( ( ( t t t t O O ) e e e S b b S ( ( t s s u ) ) a e e b t r r j e v v e e e c r r t ) ) o b s f r e o e r r a t v - u e a > r r U n s i p n d s a u o t b b e j s ( e e ) c r t v S e t r a s t e O U b p C U o s d o p b e a n d s r t c a e v e r t r e ( e e v r ) t ( e e ) r O S b t s a e t r e v e r o b s s e u r b v j e e r c S t t - a > t G e e t = S t a t e ( )

Source Code Listing

code.ts

import {LinkedList} from "../../algorithms/linked-list/code.ts";

type Observer = {
  update(subject: Subject): void;
};

class Subject {
  get counter() {
    return 0;
  }

  private readonly observers: LinkedList<Observer> = new LinkedList<Observer>();

  attach(observer: Observer): void {
    this.observers.append(observer);
  }

  detach(observer: Observer): void {
    this.observers.remove(observer);
  }

  notify(): void {
    const iterator = this.observers.createIterator();
    while (!iterator.isDone()) {
      const observer = iterator.currentItem();
      if (observer) {
        // Check if observer is not undefined
        observer.update(this);
      }

      iterator.next();
    }
  }
}

class ConcreteSubject extends Subject {
  // Concrete subject can have its own state or methods
  // that, when changed, trigger notifications
  someState = "";

  setState(newState: string): void {
    this.someState = newState;
    this.notify(); // Notify observers when state changes
  }
}

class ConcreteObserver implements Observer {
  update(subject: Subject): void {
    if (subject instanceof ConcreteSubject) {
      // Type guard
      console.log(`Updated. Subject's state: ${subject.someState}`);
    } else {
      console.log("Updated");
    }
  }
}

// List and Iterator implementations (from previous examples)
// ... (Include the List and Iterator implementations from the previous response here)

const example = {
  run(): void {
    const subject = new ConcreteSubject();
    const observer = new ConcreteObserver();

    subject.attach(observer);
    subject.setState("New State!"); // Example of state change and notification

    const observer2 = new ConcreteObserver();
    subject.attach(observer2);
    subject.setState("Another State!"); // Example with multiple observers

    subject.detach(observer); // Detach an observer
    subject.setState("Yet Another State!"); // Observer should not be notified
  },
};

Example.run();