notes

Log | Files | Refs | README

observer_pattern.md (1269B)


      1 # Observer Pattern
      2 
      3 ## Centralized Store (Observable Pattern)
      4 
      5 ```
      6 Observer pattern (object-centric)
      7 ------------------------------------
      8 
      9         +-------------------+
     10         |    UserService    |   subject owns its observers
     11         +-------------------+
     12         |         |         |
     13         v         v         v
     14    +--------+ +--------+ +--------+
     15    | View A | | View B | | Logger |
     16    +--------+ +--------+ +--------+
     17 ```
     18 
     19 The most fundamental approach is a typed store class that holds state, exposes a
     20 getState() method, and notifies subscribers on change:
     21 
     22 ```ts
     23 interface AppState {
     24   user: User | null;
     25   theme: "light" | "dark";
     26 }
     27 
     28 class Store<T> {
     29   private state: T;
     30   private subscribers = new Set<(state: T) => void>();
     31 
     32   constructor(initialState: T) {
     33     this.state = { ...initialState };
     34   }
     35 
     36   getState(): T {
     37     return { ...this.state };
     38   }
     39 
     40   setState(updates: Partial<T>) {
     41     this.state = { ...this.state, ...updates };
     42     this.subscribers.forEach((cb) => cb(this.getState()));
     43   }
     44 
     45   subscribe(cb: (state: T) => void): () => void {
     46     this.subscribers.add(cb);
     47     return () => this.subscribers.delete(cb);
     48   }
     49 }
     50 ```
     51 
     52 TypeScript generics make the store fully type-safe — setState only accepts keys
     53 that exist on your state interface.