Home » Core Java » Java Mediator Design Pattern Example

About Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.

Java Mediator Design Pattern Example

1. Introduction

In this article, we are going to talk about a design pattern – Mediator Design Pattern that is widely used in various chat application(Whats App, Instagram, Facebook etc.). Mediator design pattern is  one of the design pattern that is mainly used to handle complex communications between related objects. This design pattern act as a mediator or middleman between two communicating objects. For new programmers design patterns are very useful as they are reusable in more than one projects or programs. This design pattern also provide the solutions that help to define the system design. The best way to learn design pattern for developers is to start coding with them. This patterns normally show relationships and interactions between classes or objects. The basic idea is to increase the speed of development process by providing tested, proven development architecture.

Java programming provides various types of design patterns which allows programmers how to define a specific class, how we can extend to other classes, how we can use the basic features of Java like the inheritance, encapsulation, interfaces, data abstraction etc.  in the implementation of objects and the management of object’s properties and attributes.

Want to be a Java Master ?

Subscribe to our newsletter and download the Java Design Patterns right now!

In order to help you master the Java programming language, we have compiled a kick-ass guide with all the must-know Design Patterns for Java! Besides studying them online you may download the eBook in PDF format!

2. Java Design Patterns

Java Design Patterns are categorised into three important and widely used sub category that are discussed and elaborated below.

2.1 Creational Pattern

Creational design patterns are used for class instantiation(Creation of Object).They make the creation process more flexible and dynamic. In particular, creational patterns can provide a great deal of flexibility about which objects are created, how those objects are created, and how they are initialised. This pattern can be further Classified into class-creational patterns and object-creational patterns. While class-creational patterns use inheritance effectively in the instantiation process where as object-creational patterns use delegation effectively to get the job done. Creational design patterns are divided into six different types of design patterns.

2.2 Structural Pattern

Structural design patterns show us how to stick different elements of a system or architecture together in a flexible and extensible manner. Structural patterns help us and provides guarantee that when one of the element or pieces of system changes, the entire structure not necessarily to be modified. These design patterns are mainly concerned with class and object composition. Structural design patterns define ways to compose objects to provide new functionality.

2.3 Behavioural Pattern

These design patterns are concerned with communication between Class and objects. Behavioural design patterns are those patterns that are most specifically concerned with communication between objects. This design pattern define eleven different categories of patterns for the communication between objects.

In this post, we would elaborate one of the important and widely used behavioural patterns – Mediator Design Pattern. According to the definition, In computer engineering, the mediator pattern defines an object that encapsulates how a set of objects interact with it. This pattern is known to be a behavioural pattern due to the way it can improve the program’s running performance. This article would explain the concept regarding Mediator design pattern with a real life example. The below section will represent the pattern logically to explain each component of Mediator design pattern. Further on, we will implement Mediator design pattern in Java programming.

3. Understanding the Mediator design pattern

As we know Mediator design pattern is one of the important and widely used behavioural design pattern that allows loose coupling by encapsulating the way different sets of objects interact and communicate with each other.This type of pattern also allows that the actions of each object set to change independently with one another. Mediator design pattern permits decoupling (separation) of objects by involving a layer (Mediator) in between them so that the interaction between objects happen via the involved layer (Mediator).

In other words Mediator Design Pattern allows multiple objects to communicate with each other’s without knowing each other’s architecture. This pattern defines an object which encapsulates how the objects will interact with each other and supports very easy maintainability of the code by loose coupling. Mediator Design pattern is used to reduce communication complexity between multiple objects or classes.

Sometimes, the program is developed by using plethora numbers of classes, objects and these classes need to communicate or interact with each other. In addition to this if these classes are not loosely coupled with each other then the code management would be difficult.

By using the mediator design pattern, communication between objects is encapsulated within a mediator object. Instead of classes communicating directly with each other, classes send messages to the mediator and then the mediator send these messages to the other classes.

The below class diagram shows how the Mediator design pattern is designed.

Java Mediator Design Pattern - Class Diagram

UML Class Diagram-Mediator Design Pattern

 

In the above class diagram it mainly consists of classes, interfaces and objects that are explored below:

  1. Mediator: Mediator is an interface that defines operations which can be called by objects of colleague class for communication.In other words, Mediator defines the interface for communication between Colleague class objects.
  2. ConcreteMediator: ConcreteMediator is a class that implement the communication operations of the Mediator interface. In other words, ConcreteMediator class implements the Mediator interface and coordinates communication between Colleague objects.
  3. Colleague: Colleague is a class that defines a single, protected field that holds a reference to a mediator interface.
  4. ConcreteColleague1 and 2: ConcreteColleague1 and ConcreteColleague2 are the classes that communicate with each other via the mediator interface.  In other words, the ConcreteColleague class communicates with other colleagues through the mediator.

Mediator Design Pattern defines an object that acts as a mediator between communicating objects and removes the direct dependency between those communicating objects. The created mediator object encapsulates or hides the interaction information between classes and uses it to enable communication between the objects.

The intermediate mediator object created is not only to communicate between two objects, but it helps in interaction for a set of related objects. This mediator object is like a router in networks, which routes / controls or coordinates communication between network systems.

3.1 Real Life Example

Let us take an real life example of Mediator Design Pattern – Facebook App. We all are aware of Facebook and used in our day to day life as a platform were everyone can share there posts, videos, Images, Photos, Important Links etc. The below diagram explains how Mediator design pattern can be implemented in real life. In Facebook App we can create some specific group where everyone who has joined this group can share there posts.

Java Mediator Design Pattern - Real Time Example

Real Time Example Diagram-Mediator Design Pattern

 

Assume there is group called java programming that is created in Facebook in this group some peoples are joined such as Dave, Ram, Raj, Anu, Raju, Steve, Rahul. Suppose Ram is sharing a java programming link to this group and then the java programming group will send this shared link to all the group members who are registered with this group. Here the java programming group act as a mediator whatever message or post comes to Facebook it will route that message among all the users or members that are joined to particular Facebook group.

4. Implementing Mediator design pattern

Now, we will implement Mediator design pattern using java programming. Let us take an example of Road traffic control that is a good example of Mediator design pattern where the traffic police officer works as a mediator for communication between different vehicles. Mediator works as a router between objects and it can have it’s own logic to provide way of communication.

Road traffic police officer (RTPC) is a mediator between vehicles. It helps in communication between vehicles and co-oridates/controls and allows vehicles to stop or go forward. Two vehicles does not interact directly and there is no dependency between them. This dependency is solved by the mediator (Road traffic police officer). If Road traffic police officer is not there all the vehicles have to interact with one another and managing the vehicles will be very difficult and messy and things may go wrong.

RTPCMediator.java

class RTPCMediator implements IRTPCMediator {
	private Vehicle vehicle;
	private Road road;
	public boolean start, stop;

	public void registerRoad(Road road) {
		this.road= road;
	}

	public void registerVehicle(Vehicle vehicle) {
		this.vehicle= vehicle;
	}

	public boolean isStarted() {
		return start;
	}

        public boolean isStopped() {
		return stop;
	}

	@Override
	public void setStartedStatus(boolean status) {
		start= status;

	}
        
        @Override
	public void setStoppedStatus(boolean status) {
		stop= status;

	}
}

In the above code we have created RTPCMediator class that implements IRTPCMediator interface. Inside this class we have created two private objects vehicle, road and two public objects start, stop whose type is boolean. Also we have created several methods such as registerRoad(), registerVehicle(), isStarted(), isStopped(), setStartedStatus(), setStoppedStatus().

IRTPCMediator.java

interface Statement{
	void start();

        void stop();
}

interface IRTPCMediator {

	public void registerRoad(Road road);

	public void registerVehicle(Vehicle vehicle);

	public boolean isStarted();
        
        public boolean isStopped();

	public void setStartedStatus(boolean status);

        public void setStoppedStatus(boolean status);
}

class Vehicle implements Statement{
	private IRTPCMediator rtpcMediator;

	public Vehicle(IRTPCMediator rtpcMediator) {
		this.rtpcMediator = rtpcMediator;
	}

	public void start() {
		if (rtpcMediator.isStopped()) {
			System.out.println("Started....");
			rtpcMediator.setStartedStatus(true);
		} else
			System.out.println("Will wait to start....");
	}

        public void stop() {
		if (rtpcMediator.isStopped()) {
			System.out.println("Stopped....");
			rtpcMediator.setStoppedStatus(true);
		} else
			System.out.println("Will wait to stop....");
	}

	public void getReady() {
		System.out.println("Getting ready...");
	}

}

class Road implements Statement{
	private IRTPCMediator rtpcMediator;

	public Road(IRTPCMediator rtpcMediator) {
		this.rtpcMediator= rtpcMediator;
		rtpcMediator.setStartedStatus(true);
	}

	@Override
	public void start() {
		System.out.println("Starting permission granted...");
		rtpcMediator.setStartedStatus(true);
	}

        @Override
	public void stop() {
		System.out.println("Stopping permission granted...");
		rtpcMediator.setStoppedStatus(true);
	}

}

In the above code we have created two interfaces called Statement and IRTPCMediator in which several abstract methods are declared. We have also created two classes known as Vehicle and Road and both the classes implements Statement interface. Inside this two classes the defined abstract methods are implemented.

MediatorDesignPattern.java

public class MediatorDesignPattern {
	public static void main(String args[]) {

		IRTPCMediator rtpcMediator = new RTPCMediator();
		Vehicle marutisuzuki= new Vehicle(rtpcMediator);
		Road mgroad= new Road(rtpcMediator);
		rtpcMediator.registerVehicle(marutisuzuki);
		rtpcMediator.registerRoad(mgroad);
		marutisuzuki.getReady();
		mgroad.start();
		marutisuzuki.start();
                marutisuzuki.stop();
	}
}

Finally, we have implemented MediatorDesignPattern class in that we have created objects of IRTPCMediator class, Vehicle class and Road class. After creating objects we called several methods using this created objects such as rtpcMediator.registerVehicle(), marutisuzuki.getReady(), mgroad.start() etc.

5. Benefits of using Mediator Design Pattern

The Mediator Design Pattern provide us with the following advantages/benefits.

  • Mediator Design Pattern is very simple to understand and implement in real life examples such as chatRoom, Facebook, Air traffic control, Road traffic control etc.
  • Its one of the main advantage is that we can replace one object in the implementation with a different other object without affecting the classes and the interfaces.
  • This design pattern restrict sub classing (the class that is derived from another class). A Mediator design pattern restrain behaviour that otherwise it would be circulate among several different objects. Changing this behaviour requires sub classing which Mediator design pattern only does, Colleague classes can be reused as it is.

6. Use of Mediator Design Pattern

In the above section we have discussed benefits/advantages of Mediator design pattern. Now, in this section we will elaborate some uses of Mediator design pattern as follows:

  • Mediator design pattern is very useful when the interaction between objects is complex, we can have a central point of communication (Mediator) that takes care of interaction between objects.
  • This pattern in mainly used when there is a tight coupling between a set of communicating objects should be avoided. It is also used when there is an interaction between a set of objects needs to be changed independently.
  • In java programming the module known as Java Message Service (JMS) uses Mediator design pattern along with Observer design pattern to allow applications to subscribe and publish information to other applications effectively.
  • One of the most important key point is that we should not use Mediator design pattern just to achieve lose-coupling because if the number of mediators will increase, then it will become difficult to maintain them.

7. Demerits of Mediator Design Pattern

In this section, we will discuss about the drawbacks of Mediator Design Pattern which are as follows:

  • Disadvantage of Mediator pattern is that it centralises the communications between various components and thus the mediator pattern deals complexity of interaction for complexity in the mediator. Because a mediator hides protocols, it can become more and more complex than any individual colleague. This can make the mediator itself a large block that is hard to maintain.
  • The biggest drawback of using the Mediator design pattern is that it can develop a single point of failure. Creating a Mediator between modules can cause a performance delay as they are always communicating indirectly. We know that Mediator pattern allows loose coupling by encapsulating the way different sets of objects because of the nature of loose coupling, it’s difficult to establish how a system might react by only looking at the broadcasts.
  • Mediator Design Pattern has complexity because the mediator may handle a potentially large number of colleagues and the contents of the mediator may be very complex.

8. Mediator Design Pattern – Conclusion

In software engineering the Mediator design pattern is considered one of the most important and widely used design patterns. It is used mainly because of its potential to encapsulate interaction between sets of objects and to fulfil some business requirements. A disadvantage of this pattern often being discussed in the above section is that the mediator object can gradually get expanded and finally become excessively complex. But, because of the rigid design principles, specifically the Single Responsibility principle, we can isolate the responsibilities of a mediator into separate classes.

9. Download the Source Code

The above implemented code example can be downloaded from the below link.

Download
You can download the full source code of this example here: MediatorPattern.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of