Mediator is a behavioral design pattern which is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
Demonstrational example of Mediator Pattern is s chat room where multiple users can send message to chat room and it is the responsibility of chat room to show the messages to all users. There are two classes – User and ChatRoom, ChatRoom acts as a Mediator: User objects use ChatRoom to share their messages.
Step 1 : Create mediator class
public class ChatRoom {
public static void showMessage(User user, String message) {
System.out.println(new Date() + " [" + user.getName() + "] : " + message);
}
}
Step 2 : Create User class
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String name) {
this.name = name;
}
public void sendMessage(String message) {
ChatRoom.showMessage(this, message);
}
}
Step 3 : Use the User object to show communication between users
public class MediatorPatternDemo {
public static void main(String[] args) {
User john = new User("John");
User robert = new User("Robert");
john.sendMessage("Hi, Robert");
robert.sendMessage("Hello, John");
}
}
The output will be :
Thu Aug 20 15:37:36 EDT 2020 [John] : Hi, Robert
Thu Aug 20 15:37:36 EDT 2020 [Robert] : Hello, John