Mediator pattern defines an object that encapsulates how a set of objects interact.
Participants
Mediator - defines the interface for communication between Colleague objects.
ConcreteMediator - implements the Mediator interface.
Implements the communication and transfer the messages between the colleague objects.
ConcreteColleague - communicates with other Colleagues through its.
Before Mediator Design Pattern
Chat application
package designpattern.mediator;
public interface IChatMediator {
public void sendMessage(IUser from, IUser to, String msg);
void addUser(IUser user);
}
import java.util.ArrayList;
import java.util.List;
public class ChatMediator implements IChatMediator {
private List<IUser> users;
public ChatMediator() {
this.users=new ArrayList<>();
}
@Override
public void addUser(IUser user) {
this.users.add(user);
}
@Override
public void sendMessage(IUser from, IUser to, String msg) {
to.receive(from,msg);
}
}
public abstract class IUser {
protected IChatMediator mediator;
protected String name;
public IUser(IChatMediator med, String name){
this.mediator=med;
this.name=name;
}
public abstract void send(IUser to, String msg);
public abstract void receive(IUser from,String msg);
}
public class User extends IUser {
public User(ChatMediator med, String name) {
super(med, name);
}
@Override
public void send(IUser to, String msg) {
System.out.println(this.name+": Sending Message="+msg);
mediator.sendMessage(this, to,msg);
}
@Override
public void receive(IUser from, String msg) {
System.out.println("Delivered from "+from.name+" to "+this.name);
}
}
public class ChatClient {
public static void main(String[] args) {
ChatMediator mediator = new ChatMediator();
IUser john = new User(mediator, "john");
IUser micheal = new User(mediator, "micheal");
mediator.addUser(john);
mediator.addUser(micheal);
john.send(micheal, "hello micheal!");
micheal.send(john, "hello john!");
}
}
Output:
john: Sending Message=hello micheal!
Delivered from john to micheal
micheal: Sending Message=hello john!
Delivered from micheal to john
Mediator Pattern usage in JDK
Java Message Service (JMS) uses Mediator pattern along with Observer pattern to allow applications to subscribe and publish data to other applications.
java.util.Timer class schedule (i.e scheduleAtFixedRate) methods.
Java Concurrency Executor execute() method.
java.lang.reflect.Method invoke() method.