#
Mediator
This tutorial explains to you the design pattern named Mediator (which is a Structural Pattern).
#
Mediator Pattern - theory
Mediator
Design Pattern in Java is used when we want more objects communicate one with each other in a simple manner.
It helps to promote a looser coupling and centralizes the control. This pattern is used in message-based systems.
Take a look at the following UML diagram representing the Mediator design pattern (for my example):
In this example you can see how a list of users are defined into a mediator class. When a user send a message the others receive it.
#
Mediator Pattern - example
Here is an example of using the Mediator Design Pattern in Java:
package mediator.java.pattern.example;
public class User {
private String name;
public User(String name){
this.name = name;
}
public void sendMessage(String message){
System.out.println("The user "+name+" SEND the message '"+ message +"' to ALL ");
MediatorClass.sendToAllMessage(this,message);
}
public void receiveMessage(String message){
System.out.println("The user "+name+" receive the message: "+message);
}
}
package mediator.java.pattern.example;
import java.util.ArrayList;
import java.util.List;
public class MediatorClass {
private static List<User> users;
public MediatorClass(){
MediatorClass.users=new ArrayList<>();
}
public static void sendToAllMessage(User user, String message){
for (User u : users){
//message should not be received by the user sending it
if(u != user){
u.receiveMessage(message);
}
}
}
public static void addUser(User user){
users.add(user);
}
}
package mediator.java.pattern.example;
public class MediatorJavaPatternExample {
public static void main(String[] args) {
User robert = new User("Robert");
User john = new User("John");
User dana = new User("Dana");
MediatorClass mediator = new MediatorClass();
MediatorClass.addUser(robert);
MediatorClass.addUser(john);
MediatorClass.addUser(dana);
robert.sendMessage("Hi!");
System.out.println("\n");
john.sendMessage("Hello!");
}
}
When you run this example you will receive the following result: