ObserverVSMediator
The Problem
Scenario A β Observer territory: You are building an order service. When an order is placed, several independent systems must react: inventory decrements stock, billing generates an invoice, notifications sends an email, and analytics logs the event. The order service should not know or care what happens downstream β it just broadcasts "order placed."
Scenario B β Mediator territory: You are building a chat room. When User A sends a message, the room must check if User B is online, format the message for User B's client type (web vs mobile), throttle if User A is spamming, and log the exchange. The interaction logic lives in the coordination, not in any single participant.
Why They Look Alike
Both patterns decouple objects that need to communicate. Neither sender nor receiver holds a direct reference to the other's concrete class.
Both have a central object (Subject / Mediator) that knows about participants. Both let you add participants without modifying existing ones. The difference is in who holds the interaction logic.
The Core Difference
| Aspect | Observer | Mediator |
|---|---|---|
| Direction | One-to-many broadcast | Many-to-many coordination |
| Logic location | Each observer decides what to do | Mediator contains the coordination logic |
| Subject awareness | Subject does not know what observers do | Mediator knows the protocol between colleagues |
| Coupling | Observers are independent of each other | Colleagues communicate only through mediator |
| Analogy | Newsletter β publisher sends, subscribers react | Air traffic control β planes talk through tower |
Observer: The subject fires an event. Each observer independently decides how to react. The subject has zero knowledge of what happens next.
Mediator: The mediator receives a message from one colleague and decides what to do β routing, transforming, filtering, orchestrating responses across multiple colleagues. The logic is in the mediator.
Side-by-Side Code
Observer approach β Order events
| 1 | interface OrderObserver { |
| 2 | onOrderPlaced(order: Order): void; |
| 3 | } |
| 4 | |
| 5 | class OrderService { |
| 6 | private observers: OrderObserver[] = []; |
| 7 | |
| 8 | subscribe(observer: OrderObserver): void { |
| 9 | this.observers.push(observer); |
| 10 | } |
| 11 | |
| 12 | placeOrder(order: Order): void { |
| 13 | // Core logic |
| 14 | this.save(order); |
| 15 | // Broadcast β we don't know or care what happens |
| 16 | for (const obs of this.observers) { |
| 17 | obs.onOrderPlaced(order); |
| 18 | } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | // Each observer is independent |
| 23 | class InventoryObserver implements OrderObserver { |
| 24 | onOrderPlaced(order: Order): void { |
| 25 | this.decrementStock(order.items); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | class BillingObserver implements OrderObserver { |
| 30 | onOrderPlaced(order: Order): void { |
| 31 | this.generateInvoice(order); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | class NotificationObserver implements OrderObserver { |
| 36 | onOrderPlaced(order: Order): void { |
| 37 | this.sendEmail(order.userId, 'Order confirmed'); |
| 38 | } |
| 39 | } |
Mediator approach β Chat room coordination
| 1 | interface ChatColleague { |
| 2 | id: string; |
| 3 | clientType: 'web' | 'mobile'; |
| 4 | receive(message: FormattedMessage): void; |
| 5 | } |
| 6 | |
| 7 | class ChatRoomMediator { |
| 8 | private participants = new Map<string, ChatColleague>(); |
| 9 | private rateLimiter = new RateLimiter(); |
| 10 | |
| 11 | register(colleague: ChatColleague): void { |
| 12 | this.participants.set(colleague.id, colleague); |
| 13 | } |
| 14 | |
| 15 | send(senderId: string, text: string, targetId: string): void { |
| 16 | // Mediator contains ALL the coordination logic |
| 17 | if (this.rateLimiter.isThrottled(senderId)) { |
| 18 | const sender = this.participants.get(senderId); |
| 19 | sender?.receive({ text: 'Slow down!', type: 'system' }); |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | const target = this.participants.get(targetId); |
| 24 | if (!target) return; |
| 25 | |
| 26 | // Format per client type β mediator decides |
| 27 | const formatted = target.clientType === 'mobile' |
| 28 | ? { text, type: 'push' as const } |
| 29 | : { text, type: 'ws' as const }; |
| 30 | |
| 31 | target.receive(formatted); |
| 32 | this.logger.log(senderId, targetId, text); |
| 33 | } |
| 34 | } |
The Observer version: OrderService broadcasts, each observer reacts independently. The Mediator version: ChatRoomMediator contains routing, rate limiting, formatting, and logging logic β colleagues just send and receive.
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| One thing happens, many systems react independently | Observer | Each reaction is self-contained |
| Multiple objects need coordinated communication | Mediator | Logic lives in the coordination |
| Adding a new listener should require zero changes elsewhere | Observer | Just implement the interface and subscribe |
| The interaction protocol is complex (routing, filtering, ordering) | Mediator | Centralize the protocol |
| Objects don't need to know about each other at all | Observer | Fully decoupled |
| Objects communicate but shouldn't have direct references | Mediator | Mediator brokers the communication |
| Event-driven architecture (pub/sub, webhooks, EventEmitter) | Observer | One-to-many is the essence of events |
| UI form with cross-field validation (field A disables field B) | Mediator | Fields coordinate through a form mediator |
The Trick Question
"Your API gateway receives a request and must coordinate: authentication, rate limiting, request transformation, and routing to the correct microservice. Each step depends on the outcome of the previous one. Which pattern?"
This looks like Observer (one event, multiple handlers) but is actually Mediator (or its close cousin Chain of Responsibility). The key tell: each step depends on the previous one. Observer handlers are independent β they don't care about each other's results. Here, the gateway orchestrates a sequence with conditional logic between steps.
If the steps were independent (log the request AND check analytics AND warm the cache), that would be Observer territory.
Interview Angles
Q: Can you use both Observer and Mediator together? Yes. A Mediator can use Observer internally. Example: a ChatRoom mediator that also broadcasts "user joined" events to analytics observers. The mediator handles coordination logic; the observer handles independent side effects.
Q: How does NestJS EventEmitter relate to these patterns?
EventEmitter2 in NestJS is Observer. @OnEvent('order.created') handlers are independent observers. If you need coordinated multi-step workflows (saga), you need a mediator/orchestrator, not just events.
Q: What's the risk of a "God Mediator"? If the mediator grows to contain all business logic, it becomes a God Object. The fix: split into focused mediators (ChatMediator, NotificationMediator) or switch to Observer for the parts that are truly independent.
Q: Observer vs EventEmitter vs Pub-Sub β are they the same? Observer: subject knows its observers directly. EventEmitter: same thing, string-keyed. Pub-Sub: a broker sits between publisher and subscriber (neither knows the other). Pub-Sub is closer to Mediator because the broker can add routing logic.