Back to All Design Patterns
Pattern 19 of 22
Behavioral PatternINTERMEDIATE7 min deep dive
Mediator Pattern Pattern
Restricts direct communications between objects and forces them to collaborate only via a mediator object.
Real-World Mental Model / Metaphor:
An Air Traffic Control (ATC) tower. Airplanes do not talk directly to each other to negotiate runway landings; every pilot talks exclusively to the ATC tower, which coordinates safe spacing.
Interactive Runtime Simulator
Test and tweak inputs dynamicallyInteractive Mediator Pattern SimulatorLIVE PLAYGROUND
Interact with the controls below to see how this design pattern executes in memory at runtime.
1. Configure Observers (Subscribers):
Select Event to Emit:
EVENT BUS DISPATCH LOGS3 Active Observers
Click “Publish Event” to watch the subject notify all active subscribers.
The Problem It Solves
Tightly-coupled 'spaghetti' architectures where every component holds direct references to 10 other components.
The Architectural Solution
Extract all component-to-component interactions into a Mediator class.
Pattern Structure & Participants
| Participant | Role & Responsibility | Type |
|---|---|---|
| Mediator (Interface) | Declares notify(sender, event) | interface |
| ConcreteMediator (ATC Tower) | Coordinates interactions between colleagues | class |
| Colleagues (Planes / UI Components) | Communicate only with the Mediator | class |
Collaboration Rules:
- Colleagues only hold a reference to Mediator
- Mediator routes notifications to appropriate target colleagues
Production Code Implementation
Mediator Pattern.java
public interface ChatMediator {
void sendMessage(String msg, User sender);
void registerUser(User user);
}
public class ChatRoomMediator implements ChatMediator {
private final List<User> users = new ArrayList<>();
public void registerUser(User user) { users.add(user); }
public void sendMessage(String msg, User sender) {
for (User u : users) {
// Don't send the message back to the sender
if (u != sender) {
u.receive(msg, sender.getName());
}
}
}
} When to Use:
- •When it is hard to change some of the classes because they are tightly coupled to a dozen other classes.
- •When you cannot reuse a component in a different program because it's too dependent on other components.
When to Avoid (Anti-Pattern):
- •When interactions are simple and direct; a mediator can inadvertently evolve into an unmaintainable 'God Object'.
Staff Engineering Interview Insights & Gotchas
- Contrast Mediator vs Observer: Mediator centralizes complex multi-way communication; Observer distributes one-to-many event notifications.