What Problem It Solves
Multiple objects interact in complex ways. Without Mediator, every object knows about every other object (many-to-many coupling). With Mediator, objects only know about the mediator (many-to-one). The mediator encapsulates the interaction logic.
Mediator vs Observer
| Aspect | Mediator | Observer |
|---|---|---|
| Communication | Many-to-one (all peers through mediator) | One-to-many (subject to observers) |
| Direction | Bidirectional | Unidirectional (subject โ observer) |
| Control | Centralized in mediator | Distributed |
| Coupling | Peers don't know each other | Subject knows observers (at interface level) |
Implementation
// โโโ EXAMPLE 1 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// WHAT WE ARE IMPLEMENTING:
// An aviation control tower regulating flight paths and runway clearances for
// multiple landing airplanes.
//
// WHERE THE MEDIATOR FITS IN:
// AirportControlTower acts as the Mediator. Flight acts as the Colleague
// interface. Planes communicate solely through the tower to prevent
// collisions.
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
import java.util.ArrayList;
import java.util.List;
// --- Mediator ---
interface ChatMediator {
void sendMessage(String message, User sender);
void addUser(User user);
}
// --- Concrete mediator ---
class ChatRoom implements ChatMediator {
private final List<User> users = new ArrayList<>();
public void addUser(User user) {
users.add(user);
System.out.println(" [Room] " + user.getName() + " joined");
}
public void sendMessage(String message, User sender) {
for (User user : users) {
// Don't send back to sender
if (user != sender) {
user.receive(message, sender.getName());
}
}
}
}
// --- Colleague ---
class User {
private final String name;
private final ChatMediator mediator;
public User(String name, ChatMediator mediator) {
this.name = name;
this.mediator = mediator;
}
public String getName() { return name; }
public void send(String message) {
System.out.println(" [" + name + "] Sending: " + message);
mediator.sendMessage(message, this);
}
public void receive(String message, String from) {
System.out.println(" [" + name + "] Received from " + from + ": " + message);
}
}
public class Main {
public static void main(String[] args) {
ChatMediator chatRoom = new ChatRoom();
User alice = new User("Alice", chatRoom);
User bob = new User("Bob", chatRoom);
User charlie = new User("Charlie", chatRoom);
chatRoom.addUser(alice);
chatRoom.addUser(bob);
chatRoom.addUser(charlie);
System.out.println("\n--- Alice sends a message ---");
alice.send("Hello everyone!");
}
}Review
Help Us Improve
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Placeholder
Discussion
Share your thoughts, ask questions, or help others.
Loading comments...