Mediator Design Pattern

What is Mediator Design Pattern?

  • It falls under behavioral design pattern.
  • It reduces the communication complexity between multiple objects.
  • The pattern provides a mediator object which handles all the communication difficulties between the objects. 
  • The mediator is the communication center for the objects.
  • When an object needs to communicate with other objects, it doesn’t call the other objects directly; instead, it calls the mediator object which handles those hurdles.
  • Reduce the coupling between the objects.

Real Life Examples of Mediator Design Pattern

Example 1:

airport pathwayLet'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.

Example 2:

customer careCustomer 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.

UML Class Diagram of Mediator Design Pattern

Mediator Design Pattern Java Implementation

Step 1:

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);
    }
}

Step 2:

public class CustomerCare
{

    public static void sendMessage(Customer user, String message)
    {
        System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message);
    }
}

Step 3:

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");
    }
}

Tutorial Videos of Mediator Design Pattern

For tutorial videos, please check out the premium Software Design Pattern course on Udemy.  

Share