Mediator Design Pattern in Java

Mediator Pattern is one of the behavioral patterns as it deals with the behavior of the program. Usually a program is made up of a large number of classes. So the logic and computation are distributed among these classes. As more classes are developed in a program, the number of classes are increased, thus arising the problem of communication among these classes and it becomes much difficult to read and maintain. Therefore, the mediator pattern comes in rescue to the complexity which comes in the coding when number of classes increase.

Mediator design pattern is very helpful in an enterprise application where multiple objects are interacting with each other. Mediator design pattern is used to provide a centralized communication medium among different objects. In this pattern, objects no longer communicate directly with each other in a tightly-coupled manner that makes maintainability cost higher and not flexible to extend easily, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby implementing the lose-coupling.

For more info you can find at http://en.wikipedia.org/wiki/Mediator_pattern

Class Diagram

Mediator Pattern in Java
Example

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. The JMS API supports two models. One is point-to-point and another is the publish-subscribe model. Publish-subscribe is an implementation of the mediator pattern. The messages can be publisehd based on a particular topic. The publisher has to create a subscription to which different subscribers may subscribe. Zero or more subscribers may subscribe to receive messages on a particular message topic. The publisher and the subscriber do not know one about each other, the subscriber can even be inactive. In this case the subscriber receives the messages when it will become active.

Implementation

Let’s take an example, in an IT organization there are several Accounts, under Account there are several projects etc. So a manager can be assigned to one or more Accounts or Projects. Suppose a manger looks after only one project and assigns tasks to team members. So when the manager assigns tasks to his/her team members, team members get those tasks and start working on those tasks.

Now we will look into the implementation step by step.

Run the above test class you will see the below output.

Output

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.