Mediator

Intermediate · 13 min read · Low-Level Design, Behavioral Patterns

Replacing a web of object-to-object calls with a hub.

The idea in plain words

When many objects all talk to each other directly, you get a tangled web where every change touches everything. A Mediator is one object in the middle: the others only talk to it, and it decides who needs to know what.

The problem

Consider an air-traffic scenario — or, closer to LLD interviews, a chat room or a checkout form. In a checkout form:

The solution

Components notify the mediator about events; the mediator decides what other components should do. Each component depends only on the mediator interface.

Classic LLD example: chat room

The room can add muting, moderation, message history or rate limits without touching User.

Where you've seen it

Pitfalls

Pros and cons

Comparisons

Keeping the mediator small: one handler per message

The classic form puts every rule in one notify(sender, event) switch, which is exactly how god mediators grow. A common fix is to make the mediator a small router: each message type is a class, and each rule is a separate handler registered for that type.

Mediator vs event bus

An event bus (or message broker) also decouples senders from receivers, but it only routes messages by topic: it contains no rules about what should happen. A mediator owns the coordination logic for one context ("when the alarm is armed, lock the doors and switch off the lights").

Testing

Interview questions

  • When would you use a Mediator instead of letting objects call each other?
  • How do you prevent the mediator from becoming a god object?
  • Two users send messages to the same chat room at the same moment. How do you keep the mediator thread-safe and the message order consistent?

Further reading

Key takeaways

  • Mediator replaces many-to-many object references with many-to-one references to a hub.
  • Components notify the mediator; it coordinates the reactions.
  • Great for forms, chat rooms, workflows and device coordination.
  • Watch for god mediators; Facade simplifies access, Mediator decouples peers.
  • Keep the mediator a small router with one handler per message type, and test components and rules separately.

Previous: Iterator · Next: Memento