Observer: tell others without knowing them
Let other parts react to events without the source depending on them.
The problem
When a cache evicts an entry, metrics, logs and a write-back may all care. If the cache calls each one directly, it depends on all of them and changes whenever a new listener appears.
Subscribe and notify
The source keeps a list of listeners and calls them in order when the event happens. Listeners subscribe themselves. The source knows only the listener function's shape.
onEvict(listener: (key: string, value: V) => void) {
this.listeners.push(listener);
}
private evict(key: string, value: V) {
this.map.delete(key);
for (const l of this.listeners) l(key, value);
}
Key takeaways
- The source publishes; listeners subscribe.
- The source never imports its listeners.
- Notify only for the event promised (evictions, not deletes).
Hands-on coding exercise
A price tracker tells everyone who subscribed when the price changes, and only when it actually changes. subscribe returns a function that unsubscribes.
type Listener = (price: number) => void;
class PriceTracker {
constructor(private price: number) {}
subscribe(listener: Listener): () => void {
throw new Error("Not implemented");
}
setPrice(price: number): void {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- What does the observer pattern remove?
- A listener is added after two evictions. Which evictions does it hear?