Mediator Design Pattern: Great Negotiator

Asiri Gunasena

Published:

Design Pattern

Mediator Design Pattern

Mediator Design Pattern reduces the coupling when communicating between objects. Consider a set of objects tightly coupled and once the application grows, the complexity also improves.

 Mediator Design Pattern introduces a new layer(Mediator) and removes the interconnection between objects. Then those objects depend on the new mediator also, objects are not aware of other existing objects.

Mediator Design Pattern is heavily used in programming languages and it comes under behavioral patterns(Design Patterns)

Mediator Design Pattern’s focus is to provide a mediator to communication between objects and help to reduce the direct contact with each other. It’s simply just like a router. All objects connect with the mediator and the mediator is responsible for passing the messages between objects or a set of objects.

There are four participants in the pattern and those are used to reduce the complexity of communication in an application. Those are

  • Abstract Mediator: Definition for Mediator to communicate with Colleague objects
  • Concrete Mediator: Implementation of Abstract Mediator to communicate with Colleague objects and responsible for communication between each other.
  • Abstract Colleague: Definition for Colleague objects and Definition of logic on Colleagues
  • Concrete Colleague: Implementation of Abstract Colleague and those are communicated through the Mediator

Let’s move into an example of a Mediator Design Pattern. This will simplify the objective of the pattern.

Mediator Design Pattern Real World Example

There are a lot of real-world examples of Mediator Design patterns. Let’s take a simple example to clarify the purpose of this pattern. Consider an airport there are flights arriving and departing.  Per day there are a lot of flights arriving and departing but, use limited runaways to complete daily operations.

Consider talking to each flight and getting an opportunity to take a runaway is not applicable to real life. Also, there is a lot of traffic in some airports, and wait until get their turn.

Therefore solution introduced in an airport was the Air Traffic Controller unit which is located in a special tower called the Airport Control Tower. Flights communicate only with the Air Traffic Controller and they are responsible for communicating and managing flights. Once runaway reserves with a flight by Air Traffic Controllers then the message communicates with all flights.

The Air Traffic Controller is the Mediator and Flights are Colleagues in this example. Let’s move into the class diagram to view the overview of the concept and implementation of the Mediator example.

Mediator Design Pattern
Mediator Design Pattern Air Traffic Controller unit

Mediator Design Pattern in Java

import java.util.LinkedHashMap;
import java.util.Map;

// Define Flight related function and Abstract Colleague
interface IFlight 
{
   void land();
}

//Define Mediator related function and Abstract Mediator
interface IAirportTrafficControlMediator
{
   public void registerFlight(Flight flight);
   
   public void setLandComplete(Flight flight);
   
   public Map<String, Flight> getFlightMap() ;
}

//Implemetation of concrete Mediator ...
//Flights are register with Controller before landing. 
//Once complete the land controller romove flight from queue   
class FlightTrafficControlMediator implements IAirportTrafficControlMediator 
{
    private Map<String, Flight> flightMap = new LinkedHashMap<>();

    @Override
    public void registerFlight(Flight flight) 
    {
        this.flightMap.put(flight.getId(), flight);
    }
    @Override
    public void setLandComplete(Flight flight) 
    {
        this.flightMap.remove(flight.getId());
    }

   public Map<String, Flight> getFlightMap() {
      return flightMap;
   }    
}

// Flights connect with air controller and wait until confimation from controller 
class Flight implements IFlight 
{
   private IAirportTrafficControlMediator mediator;
   private String id;
   public Flight(IAirportTrafficControlMediator mediator,String id) 
   {
       this.mediator = mediator;
       this.id = id;
   }
   public void land() 
   {
      System.out.println("Flight Land Completed."+ getId());
      mediator.setLandComplete(this);
   }
   public void getReady() 
   {
       System.out.println("Flight Ready for landing."+ getId());
       land();
   }
   public String getId() {
      return id;
   }  
}
    
public class MediatorAirportController {
   public static void main(String args[]) {  
      IAirportTrafficControlMediator flightMediator = 
                                     new FlightTrafficControlMediator();
      Flight flight001 = new Flight(flightMediator,"F001");
      flightMediator.registerFlight(flight001);
      Flight flight002 = new Flight(flightMediator,"F002");
      flightMediator.registerFlight(flight002);
      Flight flight003 = new Flight(flightMediator,"F003");
      flightMediator.registerFlight(flight003);
      System.out.println("Flight list in a traffic>"+ flightMediator.getFlightMap());
      flight002.getReady();
      System.out.println("Flight list in a traffic>"+ flightMediator.getFlightMap());
      flight003.getReady();
      Flight flight004 = new Flight(flightMediator,"F004");
      flightMediator.registerFlight(flight004);
      System.out.println("Flight list in a traffic>"+ flightMediator.getFlightMap());
      flight001.getReady();
      System.out.println("Flight list in a traffic>"+ flightMediator.getFlightMap());  
    }
}

According to the example, flights are waiting for their turn to land. Also once a flight comes into the airport it should be registered or reserved. The Air Traffic Controller gives the approval to each flight to take their chance.

Output

Flights list in a traffic.{F001=designpattern.Flight@15db9742, F002=designpattern.Flight@6d06d69c, F003=designpattern.Flight@7852e922}
Flight Ready for landing.F002
Flight Land Completed.F002
Flights list in a traffic.{F001=designpattern.Flight@15db9742, F003=designpattern.Flight@7852e922}
Flight Ready for landing.F003
Flight Land Completed.F003
Flights list in a traffic.{F001=designpattern.Flight@15db9742, F004=designpattern.Flight@4e25154f}
Flight Ready for landing.F001
Flight Land Completed.F001
Flights list in a traffic.{F004=designpattern.Flight@4e25154f}

Advantages of Mediator Design Pattern

  • Reduce the complexity and decouple communication between objects
  • Each object is responsible for connecting with the mediator. The mediator handles the situation
  • Centralized the control into the Middle

Design Patterns Book

Design Patterns are one of the most famous solutions in programming and millions of people follow them to fix their tasks, design projects, and so on. Most of the patterns create based on basic OOP concepts (If you beginner then read our basic OOP, Encapsulation, Inheritance, Polymorphism, and Abstraction articles with great examples )

There are a lot of articles and design pattern books available with different examples to read. Other than our article if you are interested in this topic you could go through the below books as well.

BooksDescription

Head First Design Patterns: A Brain-Friendly Guide
My favorite and it’s more readable. There are good examples and they look good to beginners as well.

Design Patterns: Elements of Reusable Object-Oriented Software
There are 23 design patterns. showing how to select an appropriate pattern for your case.

Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software
There are a lot of simple examples showing how to use design patterns in the correct way. Those are based on SOLIC principles.
Design Patterns ebook online

There are a lot of design pattern ebooks on Amazon. Those design patterns are written with great examples in a different programming language. I included a few of them according to their best ranking.

ennicode

Address: 89/1 Rabbegamuwa, Handessa, Kandy, Central, Sri Lanka

Email to: Primary: [email protected]

Services

E-Learning

Company Websites

Support and Configuration work

Banners, Covers, and Post

Web Development & Configurations

Content Writing and Marketing

Contact

Ennicode