We spend this episode looking at the mediator pattern. This is a pattern that provides a great deal of flexibility. However, it is not used as often as it should be. The implementation does not always lend itself to a mediator. Instead, the design needs to be thought through enough to create one.
The Mediator Pattern Defined
As always, we will start with the “Gang of Four” intent to set the stage for our discussion.
“Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.”
It may be most comfortable to think of the mediator as a pattern that creates a communication hub. This approach allows you to have a group of objects that interact without them needing to know about everything they communicate with. This can simplify your interfaces while making it easier to manage all of those interactions. Instead of the code being spread through several objects, you can control the flow in a single class.
Applying The Pattern
In most cases, you will want to start with an interface for the mediator. This provides the input signatures that classes can use to take advantage of it. Then a concrete class should be created to implement that interface. It will also provide the logic for the various interactions. When a class is instantiated, it will register itself with the mediator. Once registered, an instance will send information to the mediator or be transmitted data through that same mechanism.
Java, PHP, C#, etc.
This pattern again works the same in almost any language. All you need to do is create an interface and then implement the same. This sort of approach is supported in all modern languages. Thus, your challenge will be designing it properly rather than language support.