Mediator Pattern is used to reduce the complexity of communication between the objects and is mainly used in enterprise applications. Objects of a system that communicate with each other are known as colleagues. The communication can be done through an interface or abstract class.
Advantages
Communication can be done easily.
Relationship can be managed easily.
Conceptual
figure
Mediator: Mediator is used to define an interface to communicate with Colleague objects.
ConcreteMediator: ConcreteMediator knows the colleague classes and keeps a reference to the colleague objects.
Colleague classes: Colleague classes is used to keep a reference to its Mediator object.
Examples
[java]import java.util.*;
public class Room
{
public static void showMessage(User user, String message)//creating a static method
{
System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message);
}
}
public class Person
{
private String name;
public String getPerson()//as the return type expected is String so String datatype is used
{
return name;
}
public void setPerson(String name)//as method doesnot return anything void is used
{
this.name = name;
}
public User(String name)
{
this.name = name;
}
public void sendMessage(String message)
{
ChatRoom.showMessage(this,message);
}
}
public class MediatorPattern
{
public static void main(String[] args)
{
Person robert = new User("John");//creating object for class Person
Person john = new User("Jackson");//creating object for class Person
robert.sendMessage("Hi! John!");
john.sendMessage("Hello! Jackson!");
}
}
[/java]
In the above example-class room, class person is a different classes but communication can be done between them using MediatorPattern class.
Output
The result will be as follows.
[java] Tue Feb 16 16:05:46 IST 2016 [John] : Hi! Jackson!
Tue Feb 16 16:05:46 IST 2016 [Jackson] : Hello! John![/java]
Summary
Key Points
Mediator Pattern - Mediator Pattern makes the communication process easy.
Mediator Pattern - Loose-coupling between the objects can be done easily.