The Mediator design pattern is easy to understand but tricky to implement. At the core of the Mediator pattern is a Mediator class that coordinates a set of different requests that are sent by objects. The objects are called Colleagues. The Colleagues let the Mediator know that they want to change, and the Mediator handles the change taking into account what effect the changes will have on the other colleagues. For example, in my car when I turn on the headlights, the panel lights dim. Something in my car tells the panel lights to dim when the headlights are switched on. The headlights represent one colleague and the panel lights, another. A Mediator tells the panel lights to turn on as soon as I start the car, and then when the headlights are switched on, the Mediator tells the panel lights to dim. If I turn off the headlight, the Mediator tells the panel lights to brighten up again. The colleagues never communicate directly with one another but instead through the mediator. The idea is to reduce the complexity by handling all of the requests in one place. This also insures loose coupling between the colleagues.
Put succinctly, the Mediator defines an object that encapsulates how a set of objects interacts. (GoF, 273). At the bottom of justifying such an encapsulation is the fact that a loosely coupled design often has many of the objects communicating with one another. The more loosely coupled, the greater the need to communicate. This can get messy if every object is telling every other object its current state and requesting them to adjust to whatever state they are entering. This would be like my headlights communicating directly with my panel lights letting them know whether they are on or off so that the panel lights can make the necessary adjustment. Add other “interested” objects, and pretty soon you have a rat’s nest to coordinate. In order to solve this dilemma, make a cleaner design and ease the interaction, the Mediator is introduced.
The Mediator’s Structure
To get started, the GoF present both a class and interactive diagram and we’ll do the same here in Figure 1:

Figure 1: Mediator Class and Interaction Diagrams
As the class diagram shows, two abstract classes, the Mediator and Colleague, each have concrete subclasses. However, a better view can be seen in the interaction diagram. You have a single concrete Mediator handling the interaction between several colleagues. In some cases, the interaction is one way and in others, two-way, but the Colleague instance always has an object reference to the Mediator. The Mediator may or may not have an object reference to the concrete colleague.
Continue reading ‘The Mediator Design Pattern: A Minimalist Example’



Recent Comments