← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Behavioral Patterns

🤝Mediator Pattern

Define an object that encapsulates how a set of objects interact — promote loose coupling by keeping objects from referring to each other explicitly.

📌 Key IdeaInstead of N×(N-1) links between UI widgets or services, each colleague notifies Mediator; mediator orchestrates others. Think chat room, dialog coordinating inputs, enterprise service bus style routing.
🖼

Visual

🤝 Colleagues talk through mediator
      ChatRoom (mediator)
       /    |    \
   UserA  UserB  UserC   // users don't reference each other directly

Hub-and-spoke replaces mesh — easier to change interaction rules in one place.

✅

When to Use

  • Many objects interact in complex ways — hard to track direct references.
  • UI forms where enabling one field affects several others.
  • Air traffic control style coordination — rules centralized.
🚫

When NOT to Use

  • Simple one-to-one relationships — mediator is ceremony.
  • Mediator risks becoming a god object — split bounded contexts.
🚨

Anti-Pattern (What NOT to Do)

Peers reference each other directlyBadjava
class UserA {
    UserB b;
    void send(String msg) { b.receiveFromA(msg); }
}
// Adding UserC → edit A, B, ... mesh explosion
N² coupling — change one participant, ripple everywhere.
✅

The Right Way

Room mediates — peers only know mediatorGoodjava
interface Chat {
    void join(User u);
    void say(User u, String msg);
}

record User(String name, Chat room) {
    void say(String m) { room.say(this, m); }
}
Chat implementation forwards messages — rules live in one place.
⚖️

Pros & Cons

👍 Pros
  • Decouples colleagues — swap interaction policy without touching each class.
  • Simplifies reuse of individual components.
👎 Cons
  • Mediator itself can grow huge.
  • Indirection — harder to trace flow than explicit calls.
🔀

Common Confusions Cleared Up

Mediator vs Observer

Observer broadcast one-to-many notifications (subject doesn't orchestrate detailed dialogue). Mediator actively coordinates multi-step protocols between peers.

Mediator vs Facade

Facade simplifies outward API to subsystem (often one-way convenience). Mediator manages peer-to-peer conversations behind the scenes.

🎤

Interview Q&A

🔮

Likely Follow-up Questions

  • When does Mediator become an anti-pattern (fat controller)?
🧾

Quick Cheat Sheet

IntentCentral hub for colleague interactions.
vs ObserverOrchestrate vs broadcast.
RiskGod mediator.
🔗

Related Topics