Mediator Pattern Demo
Interfaces:
package MediatorPatternDemo;
// Colleague interface
interface Colleague {
void sendMessage(String message);
void receiveMessage(String message);
String getName();
}
package MediatorPatternDemo;
interface Mediator {
void sendMessage(String message, Colleague colleague);
void sendMessageAll(String message, Colleague colleague);
}
Classes
package MediatorPatternDemo;
// Concrete Mediator
class ChatRoom implements Mediator {
public void sendMessage(String message, Colleague colleague) {
// Broadcast the message to other colleagues
System.out.println(colleague.getName() + " sends message: " + message);
}
public void sendMessageAll(String message, Colleague colleague) {
// Broadcast the message to other colleagues
System.out.println(colleague.getName() + " sends message: " + message + " to Entire Chatroom");
}
}
Driver
In the example above, the Mediator
interface defines the communication contract for mediators. The ChatRoom
class is a concrete mediator that implements the Mediator
interface and manages the communication between colleagues.
The Colleague
interface defines the communication contract for colleagues. The User
class is a concrete colleague that implements the Colleague
interface. Each user communicates with other users through the mediator (the chat room). When a user sends a message, it goes through the mediator, which broadcasts the message to other colleagues.
By using the Mediator pattern, the users (colleagues) are decoupled from each other and rely on the chat room (mediator) to facilitate communication. The chat room handles the logic of routing messages between colleagues, allowing for easier maintenance and flexibility. The Mediator pattern is particularly useful when there are complex interactions and dependencies between objects, as it centralizes and organizes the communication logic.