patterntypescriptTip
Mediator Pattern: Replace Chaotic Peer-to-Peer Dependencies
Viewed 0 times
mediator patternbehavioral patternevent buscomponent communicationdecouplingcentralized logic
Problem
In a complex UI or system, components communicate directly with each other. As the number of components grows, the number of direct connections grows quadratically, making the system fragile.
Solution
Introduce a mediator that all components know. Components send events to the mediator, which decides which other components to notify, centralizing communication logic.
interface Component { notify(event: string, data?: unknown): void; }
class DialogMediator {
private components = new Map<string, Component>();
register(name: string, component: Component): void {
this.components.set(name, component);
}
handle(sender: string, event: string, data?: unknown): void {
if (sender === 'search' && event === 'input') {
this.components.get('results')?.notify('filter', data);
this.components.get('clearBtn')?.notify('show');
}
if (sender === 'clearBtn' && event === 'click') {
this.components.get('search')?.notify('clear');
this.components.get('results')?.notify('reset');
this.components.get('clearBtn')?.notify('hide');
}
}
}Why
Mediator reduces N*(N-1)/2 peer connections to N connections to a central hub. Changing how components interact requires changing only the mediator, not each component.
Gotchas
- Mediators can become god objects if too much orchestration logic accumulates. Split large mediators by domain.
- Event bus/pub-sub systems are a decentralized form of mediator — the pattern applies even without a central class.
- The mediator increases indirect coupling: components depend on the mediator knowing about all event types.
Revisions (0)
No revisions yet.