Design Pattern

Mediator Pattern Design Patterns in Java

The mediator pattern comes under behavioral patterns in object-oriented programming. In the mediator pattern, an object is defined which stores the information about the interaction between a set of objects. It is considered to be a behavioral pattern because it has the capability to alter the operational behavior of the program.

The mediator pattern

According to the Gang of Four:

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently

Generally, a program is composed of a various number of classes. The classes are each assigned, logic and computation, in the program. As the number of classes, in the program increases, especially during the maintenance, the communication between these classes becomes complex and difficult. Due to this issue, the program not only becomes harder to read but it also becomes harder to maintain. Moreover, it is difficult to change the program, because the changes can affect the codes in various other classes.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

The mediator patterns enclose the information of the communication, between the objects in the mediator object. The objects, in the program, do not need to communicate directly with each other. They communicate through the mediator object. Using mediator pattern, the dependency of the communicating objects on each other is reduced along with avoiding the coupling between them.

UML class diagram for Mediator Design Pattern

Let’s see the following UML diagram about the mediator design pattern.


The classes and objects participating in this pattern are:
Mediator 

  • It defines an interface for communicating with Colleague objects.

ConcreteMediator

  • It implements cooperative behavior by coordinating Colleague objects knows and maintains its colleagues.

Colleague classes

  • Each Colleague class knows its Mediator object each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.

Benefits of Mediator Patterns

Behavioral object patterns use object composition rather than inheritance. Some of these patterns describe how a group of peer objects cooperate to perform a task that no single object can carry out by itself. An important issue here is how peer objects know about each other. Peers could maintain explicit references to each other, but that would increase their coupling. In the extreme, every object would know about every other. The Mediator pattern avoids this by introducing a mediator object between peers. The mediator provides the indirection needed for loose coupling.

To design, versatile and reusable object-oriented software, there is 23 well-known Gang of Four (GoF) design patterns, the mediator pattern is one of them. There are certain problems that mediator pattern caters. The tight linkage or coupling between the objects, which interact, needs to be avoided. There should be a possible way of changing the communication information between the interacting objects, without having to affect other interacting objects.

To define a set of communicating objects by accessing and updating them directly cane be unbendable because it would tightly link the communicating objects to each other and would make it impossible to alter the communication information directly, without having to change the interacting objects. The objects become impossible to be reused or be tested, because of this issue. The objects that are tightly linked to each other are hard to implement, test, change or reuse because they hold the information and details about many other objects.

When Would We Use This Pattern?

The mediator pattern defines a separate mediator object that encases the communication between a set of objects. The objects in a program refer to the mediator object, in order to store their interaction with other objects instead of communicating directly. Only the mediator object controls and coordinates the interaction between the communicating objects, not allowing them to interact with each other directly. This way the objects are loosely coupled, the objects only hold the information about their mediator object and have no information about each other.

The structure of the mediator pattern is such that there is a mediator object which defined the communication interface for interaction between the objects. Then, there is a Concrete Mediator object, this object holds all the information about the objects and their purposes for the inter-communication, the same object is responsible for the implementation of the mediator interface and the coordination of the communication between the objects. Colleague object is responsible for defining the interface for interaction with other Colleagues. The Concrete Colleagues object is responsible for implementation of the Colleague interface and the communication with other colleagues, through the mediator object.

Mediator Pattern Example in JDK

  • java.util.Timer class scheduleXXX() methods
  • Java Concurrency Executor execute() method.
  • java.lang.reflect.Method invoke() method.

Example of Mediator Design Pattern

In this implementation of Mediator design pattern, we’ll use this pattern in the context of a chatroom application. In this application, multiple users can send message to chat room and it is the responsibility of chat room to show the messages to all users. Here I am going to create two classes User and ChatroomMediator. And User class uses ChatroomMediator for using group chat between users to share the messages.

Step 1: Create mediator class.
ChatroomMediator.java

import java.util.Date;

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

Step 2: Create user class

User.java

public class User {
   private String name;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public User(String name){
      this.name  = name;
   }

   public void sendMessage(String message){
      ChatroomMediator.showMessage(this,message);
   }
}

Step 3: Let’s create demo class and use the User object to show communications between the users in the chatroom.

MediatorPatternDemo.java

public class MediatorPatternDemo {
   public static void main(String[] args) {
      User dinesh= new User("Dinesh");
      User anamika= new User("Anamika");

      dinesh.sendMessage(" Hey! Anamika!");
      anamika.sendMessage("Yes! Dinesh!");
   }
}

Step 4: Let’s run this application and verify the output.

Thu Dec 07 06:06:56 IST 2017 [Dinesh] : Hey! Anamika!
Thu Dec 07 06:06:56 IST 2017 [Anamika] : Yes! Dinesh!
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago