Skip to content

Mediator

Roberto Fronteddu edited this page Jan 18, 2023 · 1 revision

The Mediator is a Behavioral Design Pattern. The Mediator encapsulates how a set of objects interact with each other reducing coupling between them. The primary object of a mediator is to streamline the communication between multiple objects.

Usefull when

  • We have complex interactions between objects.

UML

mediator uml

  • Mediator: Defines the interface for interacting with the colleague objects
  • ConcreteMediator: If the mediator is abstract/interface, in this class we would have the references of the concrete colleague objects. If a colleague change, the mediator will notify all the others about that change.
  • Colleague: Knows about the mediator and communicates with it.

Implementation steps

Define the mediator

  • The mediators define a generic method which is called by other objects.
  • This method needs to know which object has changed and optionally the property which has changed.
  • This method will also notify all the others about the state change.

Mediator needs to know about all the participants in the mediation.

  • You can achieve this by having the object register into the mediation or by having the mediator create these objects.

Design Considerations

  • The mediator should identify which object has sent the change notification to filter out that object in the notifications.
  • Notifications must be fast or they can compromise system performance.
  • If the mediator handles all routing between objects, it can become a complicated part of the code.
  • We can use the observer pattern to implement the notification mechanism used to notify the mediator.

Comparison with Observer

Mediator

  • The intent is to encapsulate complex interaction between objects.
  • Specific to the objects being mediated

Observer

  • The intent is to define a one-to-many relationship between objects.
  • Pattern is fairly generic and it can be used with any class.

Pitfalls

  • Can get out of hand as complexity increases.

Real-Life Examples

  • javax.swing.ButtoGroup takes care of making sure that only buttons in a group are selected. Participating Buttons notify the mediator when they are selected.
Clone this wiki locally