Mediator Design Pattern Implementation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We will see another behavioural pattern in this article. This will deal with Mediator Design Pattern Implementation.

Mediator Design Pattern Implementation:

It can be defined as follows.

Defines 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.

Generic class diagram for mediator pattern can be shown as

Mediator Design Pattern

Mediator Design Pattern

  • Mediator: An interface which defines methods for communication with Colleague implementations.
  • ConcreteMediator: Has reference to Colleague implementations and knows implementations.
  • Colleague: Keeps a reference to Mediator implementation.

Mediator Design Pattern Implementation:

Consider we want to build a chat application and our requirements are as below.

  • Multiple users can be added into chat room.
  • Those users need not know about each other, if they know about each other directly, then all users will have to keep reference to all other users, which is complicated structure. We do not want that.
  • We want to have a common mediator which communicates with all users.

Our approach for mediator design pattern implementation would be as below.

  • We will create ChatRoom as Mediator and ChatRoomImpl class is its implementation.
  • We will create a Participant which is a Colleague, User is its implementation.

ChatRoom.java

ChatRoomImpl.java

Participant.java

User.java

Mediator Example Class Diagram

Mediator Pattern Example

Mediator Pattern Example

Mediator design pattern implementation is ready, let us test it out. Create few users and make one user send some message and all users will receive it through ChatRoom which acts as Mediator.

ChatApp.java

This prints below

Prasad is sending a messageHello friends
Aniket Received Message Hello friends
Harish Received Message Hello friends
Amol Received Message Hello friends

I hope this article helped understand mediator design pattern implementation

Share Button

Leave a Reply

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