Mediator Pattern
1 min readRapid overview
Mediator Pattern
TL;DR
The Mediator pattern introduces a central hub that coordinates interactions between components so they never reference each other directly, replacing a tangle of many-to-many dependencies with a clean star topology. It shines for complex UI orchestration; the interview distinction is that a mediator coordinates specific interactions between known parties, whereas an observer simply broadcasts changes to anonymous listeners.
Why it matters
- Prevents components from directly depending on each other.
- Centralizes complex UI orchestration.
How it works
Example (TypeScript)
type Event = { type: 'open' | 'close' };
class UIHub {
private handlers: Array<(event: Event) => void> = [];
register(handler: (event: Event) => void) { this.handlers.push(handler); }
notify(event: Event) { this.handlers.forEach((handler) => handler(event)); }
}
const hub = new UIHub();
hub.register((event) => event.type === 'open' && console.log('panel opened'));
hub.notify({ type: 'open' });
Quick recall Q&A
Q: Mediator vs Observer? A: Observer broadcasts changes to many listeners; Mediator coordinates specific interactions.