Mediator - Harsh4999/Design-Patterns GitHub Wiki

Mediator

Use

  • Removes complexity between object interaction and collaboration
  • Due to this encapsulation there is a loose coupling between the interacting objects
  • If a state of an object changes it will only notify mediator and next mediator will take care of notifying all the objects it knows
  • If somebody sends a notification to mediator it will in reverse send us info
  • If we want to add/remove any object from our collaboration of objects we only need to make changes at mediator.

UML

  • Mediator: Defines interface/concrete class for interacting with colleague object.
  • Concrete Mediator: If mediator is interface we implement and build this concrete class it has references of all participating objects
  • Colleague: All collaboration objects. It needs to maintain a reference to the mediator.
  • Concrete Colleagues: Have reference to mediator also handle methods which help mediator send/receive state info

Implementations

  • Create mediator can be abstract or direct concrete.
  • Need to provide a method to receive notification from colleague about state change information. The method should accept the colleague object as argument as it doesn't want to send notification again to the same object.
  • Mediator needs to know all colleagues
  • We need to handle change-notify-change loop. It happens when object is not sure if it's state changed because of mediator notification or by normal change. There is some risk for infinite loop.
  • Mediator should be able to identify who sent the notification
  • If notification method is slow it may severely affect performance.
  • Mediator streamlines the communication between multiple objects
  • Eg: ButtonGroup in swing framework, Dispatcher Servlet in spring