Listen to this post
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. (GoF)
Modern development tools often offer drag-and-drop mechanisms for creating graphical user interfaces, database connections, and other system elements. It is not advisable to embed business logic in the code these tools generate, as it becomes difficult to test, reuse, and modify.
A Mediator can be introduced to encapsulate all coupling between the generated code and the handcrafted application logic. The Mediator contains only the “wiring” between these elements. The elements do not couple to each other directly in any way.
Qualities and principles
The Mediator fundamentally promotes decoupling in the system. It only contains connection logic, nothing more, and thus is strongly cohesive. The interface of the Mediator is derived from the needs of the rest of the system, which are its clients. The Mediate promotes reuse and eliminates all potential redundancies in connection logic.
The Mediator itself is a candidate for creating a Mock allowing for easier testing of all the elements that couple to it. Testing the Mediator itself is an integration issue, and thus it will be tested less frequently than other parts of the system.
Questions and concerns
Because the Mediator can only be tested in integration, care should be taken to ensure that it does not contain complex failure modes. Ideally, the Mediator should have no significant application logic beyond dispatching requests.
If flexible connections are needed the Observer can be used when implementing the Mediator. If any significant logic is required (caching, etc…) then a Proxy should be used to add it, making it testable as a separate issue.
Mediators can serve as a kind of “app roadmap” since all events, requests, and services are routed through it.