Javatpoint Logo
Javatpoint Logo

Mediator Pattern

A Mediator Pattern says that "to define an object that encapsulates how a set of objects interact".

I will explain the Mediator pattern by considering a problem. When we begin with development, we have a few classes and these classes interact with each other producing results. Now, consider slowly, the logic becomes more complex when functionality increases. Then what happens? We add more classes and they still interact with each other but it gets really difficult to maintain this code now. So, Mediator pattern takes care of this problem.

Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintainability of the code by loose coupling.


Benefits:

  • It decouples the number of classes.
  • It simplifies object protocols.
  • It centralizes the control.
  • The individual components become simpler and much easier to deal with because they don't need to pass messages to one another.
  • The components don't need to contain logic to deal with their intercommunication and therefore, they are more generic.

Usage:

  • It is commonly used in message-based systems likewise chat applications.
  • When the set of objects communicate in complex but in well-defined ways.

UML for Mediator Pattern:

Mediator Pattern

Participants:

  • ApnaChatroom :- defines the interface for interacting with participants.
  • ApnaChatroomImpl :- implements the operations defined by the Chatroom interface. The operations are managing the interactions between the objects: when one participant sends a message, the message is sent to the other participants.
  • Participant :- defines an interface for the users involved in chatting.
  • User1, User2, ...UserN :- implements Participant interface; the participant can be a number of users involved in chatting. But each Participant will keep only a reference to the ApnaChatRoom.

Implementation of Mediator Pattern:

Step 1:

Create a ApnaChatRoom interface.

Step 2:

Create a ApnaChatRoomIml class that will implement ApnaChatRoom interface and will also use the number of participants involved in chatting through Participant interface.

Step 3:

Create a Participant abstract class.

Step 4:

Create a User1 class that will extend Participant abstract class and will use the ApnaChatRoom interface.

Step 5:

Create a User2 class that will extend Participant abstract class and will use the ApnaChatRoom interface.

Step 6:

Create a MediatorPatternDemo class that will use participants involved in chatting.

Output:

Mediator Pattern






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA