Java Behavioral Design Patterns – Mediator Design Pattern

In this article, we will understand Mediator Design Pattern. This pattern is categorized under behavioral pattern as it can alter the program’s running behavior.

In some cases, the program is made up by using many numbers of classes and these classes need to communicate with each other. In addition to this if these classes are tightly coupled with each other then in it would be a code management issue in long run.

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 the mediator send these messages to the other classes.  So, in short, this pattern can be used when you see:

  • a tight coupling between a set of interacting objects should be avoided.
  • an interaction between a set of objects needs to be changed independently.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Mediator Design Pattern by Example

To understand this pattern we will take an open portal example. In this example portal will act as a mediator and it will share the messages across users in the open chat room.

For illustration, we can have our portal class with a simple static method that will show a message.

OpenPortal Class

Note above class has a single static method which displays which user has sent the message.

Let us define our portal users:

The user class has a sendMessage method which in turn uses static method exposed by the portal to broadcast message.

Running the Example

Running this demo is as easy as eating an apple pie 🙂

We have created 2 users and these two users broadcast messages in the chat room.

Output

Advantages

  • Mediator pattern provides maintainable code because here the mediator class which handles all the communications between different classes.
  • This pattern supports loose coupling as this reduces the dependencies between communicating objects.
  • As it supports loose coupling it is possible to change the interaction between a set of objects independently without affecting the remaining code.

Conclusion

In this article, we understood Mediator Design Pattern with the help of a simple example. The source code is available in our Github repository.

Download Code

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

Your email address will not be published. Required fields are marked *