Mediator Design Pattern in Java
Mediator is a middle object. Objects talk to the mediator, not directly to each other. This removes tangled connections.
Real life example
An air traffic controller. Planes talk to the tower, not to each other.
When to use
Many objects talk to many other objects and the code is becoming messy.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
import java.util.*;
public class Main {
public static void main(String[] args) {
ChatRoom room = new ChatRoom();
User ram = new User("Ram", room);
User sita = new User("Sita", room);
ram.send("Hi"); // Sita got 'Hi' from Ram
}
}
class ChatRoom { // the mediator
private List<User> users = new ArrayList<>();
void join(User u) { users.add(u); }
void send(String msg, User from) {
for (User u : users)
if (u != from) u.receive(msg, from.name);
}
}
class User {
String name;
private ChatRoom room;
User(String name, ChatRoom room) { this.name = name; this.room = room; room.join(this); }
void send(String msg) { room.send(msg, this); }
void receive(String msg, String from) { System.out.println(name + " got '" + msg + "' from " + from); }
}Output
Sita got 'Hi' from Ram