Mediator Pattern

This lesson discusses how the mediator pattern centralizes interaction amongst a number of interacting objects reducing coupling and dependence among them.

What is it ?

A mediator is defined as a person who makes people involved in a conflict come to an agreement. The pattern definition however, isn't violent and says the pattern is applied to encapsulate or centralize the interactions amongst a number of objects. Object orientated design may result in behavior being distributed among several classes and lead to too many connections among objects. The encapsulation keeps the objects from referring to each other directly and the objects don't hold references to each other anymore.

Formally, the pattern is defined as encouraging loose coupling among interacting objects by encapsulating their interactions in a mediator object, thus avoiding the need for individual objects to refer to each other directly and allowing to vary object interactions independently.

A mediator controls and coordinates the behavior for a group of objects. The objects only communicate with the mediator or the director and don't know of the other objects.

The mediator pattern should be applied when there are many objects communicating in a well-structured but complex manner resulting in interdependencies that are hard to understand. The participant objects in such a scheme don't lend themselves for reuse because of dependence on so many other objects.

Since the interaction rules or behavior is isolated in a single mediator class, it becomes easier to change. Also note that in the absence of the mediator, the objects are engaged in many-to-many interactions but when the mediator is introduced the interactions become one-to-many between the mediator and the other participating objects.

Get hands-on with 1200+ tech skills courses.