Mediator Pattern

Mediator Pattern is a #Design Pattern that encapsulates and localise how a set of objects interact with each other, especially the collective behaviour. A Mediator object can be seen as an intermediary between objects or hub of communication where they interact with each other indirectly. In this way, we could make changes to their behaviour independently without increasing coupling# between them. The reason is that with Object-Oriented Programming (OOP), we tend to have multiple objects that interconnected to each other (dependencies), which cause a change in one might affect others, thus the coupling between them can be too tight.

The Gang of Four advised to use Mediator Pattern when

  • Multiple objects communicate in well-defined but complicated (to be understandable) ways.
  • Reduction of reusuability of an object due to dependencies and communication to other objects.
  • A behaviour that’s distributed between several classes should be customisable without tons of subclassing.

Unlike #Observer Pattern, Mediator object and its colleagues (clients) know each other. Colleagues class will send and request services from Mediator object in order to interact with other colleague which one may not know about. Mediator object serves the request within its local scope and call the cooperative behaviour by routing requests between the required colleagues. Of course, the Mediator object needs to identify the colleague to search for the appropriate action.

Mediator Pattern could also incorporate #Observer Pattern to implement Publish/Subscribe Protocol as a communication mechanism. Colleagues, implemented as subjects, will notify Mediator, implemented as observer, in an event of interests where the Mediator object calls other colleagues according.

Links to this page
  • Observer Pattern

    If the updates become too complicated to handle, especially when observer is subscribing to multiple subjects, a change manager class is needed to manage the hassle so in the case when multiple subjects changes, the observer will be notified only once. Such class should be in Mediator Pattern# and Singleton Pattern#. It can be with simple approach or directed-acyclic graphs (DAG) approach. Simple change manager will update all the registered observers of each subject. DAG change manager instead handles the DAG of dependencies between subjects and their observers which is usually preferable if an observer subscribes to multiple subjects as it will update once to observer upon a change of multiple subjects.

  • Design Pattern
#oop