Observer định nghĩa one-to-many dependency: khi một object (Subject/Observable) thay đổi state, tất cả dependents (Observers) được notify tự động.
Ví dụ TypeScript:
typescript
class EventEmitter {
private listeners = new Map<string, Function[]>()
on(event: string, cb: Function) {
if (!this.listeners.has(event)) this.listeners.set(event, [])
this.listeners.get(event)!.push(cb)
}
emit(event: string, data?: unknown) {
this.listeners.get(event)?.forEach(cb => cb(data))
}
}- Trong JavaScript:
EventEmittercủa Node.js,addEventListenertrong DOM, RxJS Observable đều là Observer pattern. - React:
useEffectvới dependency array là lazy Observer; Redux store notify components khi state thay đổi. - Pub/Sub là biến thể: thêm message broker trung gian, subject và observer không biết nhau trực tiếp (khác Observer thuần).
- Dùng khi: cần event-driven architecture; khi một thay đổi trigger nhiều phản ứng không biết trước.
- Không dùng khi: dependency graph phức tạp gây 'observer hell' — khó trace execution flow.
Observer defines a one-to-many dependency: when a Subject/Observable changes state, all its dependents (Observers) are notified automatically.
TypeScript example:
typescript
class EventEmitter {
private listeners = new Map<string, Function[]>()
on(event: string, cb: Function) {
if (!this.listeners.has(event)) this.listeners.set(event, [])
this.listeners.get(event)!.push(cb)
}
emit(event: string, data?: unknown) {
this.listeners.get(event)?.forEach(cb => cb(data))
}
}In JavaScript: Node.js EventEmitter, DOM addEventListener, and RxJS Observable are all implementations of Observer.
- In React:
useEffectwith a dependency array is a lazy Observer; the Redux store notifies components when state changes. - Pub/Sub is a variant: a message broker is added in the middle so that subjects and observers don't know about each other directly (unlike pure Observer).
- Use it when building event-driven architecture or when a single change should trigger multiple unpredictable reactions.
- Avoid it when the dependency graph becomes complex enough to create 'observer hell', making execution flow hard to trace.