Let's consider Air Traffic Control (ATC) which is used to control the air traffic. The primary purpose of ATC is to prevent collisions between planes during landings and takeoffs.
Let's suppose three planes are trying land on a particular pathway. If there is no ATC, those will collide each other. ATC communicates with all the planes that are trying to land on that pathway. ATC decides which plane needs to land first and then the next. By this way, it is overcoming the big accident.
Customer care is another example of Mediator Design Pattern. Let's suppose if you bought a laptop, and it had some technical problems.
What would you do?
First
You will try to contact customer care by phone or mail. Here, customer care takes your query and analyses the query and forwards that query to the technical department.
Second
The technical department finds an answer for your query and conveys it to the customer care department.
Third
Customer care will convey the answer to us.
Here, customer care is playing a mediator role.
public class Customer
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Customer(String name)
{
this.name = name;
}
public void sendMessage(String message)
{
CustomerCare.sendMessage(this, message);
}
}
public class CustomerCare
{
public static void sendMessage(Customer user, String message)
{
System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message);
}
}
public class MediatorDemo
{
public static void main(String[] args)
{
Customer rakesh = new Customer("Rakesh");
Customer lenin = new Customer("Lenin");
rakesh.sendMessage("Laptop is generating more heat");
lenin.sendMessage("Please check the battery");
}
}
For tutorial videos, please check out the premium Software Design Pattern course on Udemy.