Behavioral Patterns «Prev Next»

Lesson 9Mediator Pattern Motivation
ObjectiveIdentify interaction problems that require the Mediator design pattern.

Problems That Require the Mediator Design Pattern

The Mediator pattern becomes useful when the main design problem lies in the interactions among several objects. These participants, called colleagues, may perform local tasks while carrying detailed knowledge about one another. As the collaboration grows, each colleague may need to know which peers exist, what operations they provide, and when to invoke them. The resulting network is difficult to understand, test, and change.

The Mediator pattern defines an object that encapsulates how a set of objects interact. Colleagues report events or request coordination through the mediator instead of maintaining a dense network of direct references to one another. The mediator contains the rules that govern the collaboration, while each colleague concentrates on its primary responsibility. This arrangement reduces coupling among concrete colleagues, but it does not eliminate dependencies. Each colleague still depends on a mediator-facing contract, and the mediator normally understands the roles involved in the workflow.

When Object Interactions Become the Problem

Direct communication is not inherently poor design. If two objects have a small, stable, and cohesive relationship, a direct method call may be the clearest solution. The need for a mediator emerges when several participants share nontrivial coordination rules and the following symptoms begin to appear:

  1. Dense dependencies: Colleagues store references to many concrete peers and call them directly. Understanding one class requires understanding much of the surrounding object network.
  2. Scattered interaction rules: The steps of a workflow are distributed across several classes, so no single place expresses the complete collaboration or its valid sequence.
  3. Cascading modifications: Adding a participant or changing a communication protocol requires edits to multiple existing classes that should not own the new rule.
  4. Reduced reuse: A colleague cannot be reused easily because it assumes the presence, interfaces, or behavior of several specific peers.
  5. Mixed responsibilities: A class performs its local task while also coordinating unrelated participants, weakening cohesion and the Single Responsibility Principle.
  6. Inconsistent sequencing: Different colleagues implement similar coordination rules differently, creating invalid state transitions and defects that are difficult to reproduce.

One symptom does not automatically justify Mediator. Use the pattern when centralizing a cohesive set of interaction rules makes the collaboration easier to understand and change. Observer, Command, a state machine, or a domain service may be better when the actual problem is notification, request representation, state transitions, or business behavior.

Direct Communication Works for Simple Collaborations

Consider Object A and Object B in a small collaboration. If the relationship belongs naturally to both objects and is unlikely to expand, direct references keep the design explicit and avoid an extra level of indirection. Each object can call the other through a narrow interface, and a developer can follow the interaction without consulting a third participant.

Figure 1: Point to Point Communication in  the case of two objects
Figure 1: Point to Point Communication in the case of two objects

A mediator in every two-object relationship adds structure without necessarily improving the design. The decision should depend on complexity and responsibility, not merely on a method call.

Many Direct References Create a Communication Maze

The situation changes as more objects participate. A fully connected set of five objects can have ten pairwise relationships, following n(n - 1) / 2. Real systems are not always fully connected, but the expression illustrates how rapidly relationships can grow. Every new colleague can introduce dependencies and another protocol.

In a dense collaboration, each colleague may need to know when to call its peers, what information to send, and how to react when a peer fails or changes state. Coordination logic becomes duplicated or fragmented. Tests require many concrete collaborators, and a change that should be local can ripple through classes that do not own the affected policy.

Figure 2: Point-to-Point Communication with an increased number of objects.
Figure 2: Point-to-Point Communication with an increased number of objects.

Figure 2 represents a dependency problem, not a prohibition against direct references. Colleagues may still communicate directly when the relationship belongs naturally to their responsibilities. Mediator encapsulates the complex many-object interaction.

Coordinating an Intersection Without Direct Light-to-Light Coupling

A traffic-light intersection provides a concrete example. Suppose a pedestrian presses the crossing button on the north side. In a direct-communication design, the north control might attempt to command the other lights itself. It would need knowledge of vehicle directions, signal phases, clearance timing, pedestrian indications, acknowledgments, and failure conditions. That knowledge is much broader than the local responsibility of accepting a pedestrian request or displaying a signal.

1) The North light must synchronize with the other lights.
1) Suppose the pedestrian wants to cross the street and pushes the button on the North light. The north light must now synchronize with the other lights

The request affects more than one lamp. East-west vehicle signals must first enter a phase that prepares traffic to stop. The system must coordinate the request with the current intersection state rather than allowing a single light to make an isolated change.

2) It has to tell the east and west lights to turn yellow, then red
2) It has to tell the east and west lights to turn yellow, then red. It also has to wait until they respond that they have in fact done so.

After the vehicle signals reach red, the controller must enforce a safe clearance interval and verify that the required phase has been reached. Only then can the appropriate pedestrian indication change to walk. Treating these steps as intersection-wide policy prevents individual lights from implementing conflicting versions of the safety sequence.

3) It must also tell the south light to provide a walk signal.
3) It must also tell the south light to provide a walk signal. The south light must also respond.

Later transitions must coordinate the same participants. Protected turns, emergency preemption, and sensors introduce more interactions. If each signal commands and queries the others, every device acquires intersection-wide responsibilities and the design becomes difficult to verify.

4) Every change in any light requires all four lights to go through a complicated sequence of request and response.
4) Every change in any light requires all four lights to go through a complicated sequence of request and response

A traffic mediator provides one location for the phase-transition policy. The north control reports the request to the mediator, which evaluates the current phase, coordinates the vehicle signals, enforces safety conditions, and enables the walk indication only when valid. Individual lights expose operations such as showYellow(), showRed(), and showWalk(), but do not decide the global sequence.

A safety-critical mediator can use an explicit state machine with defined transitions, timeouts, fault states, and fail-safe behavior. The pattern identifies where interaction policy belongs; it does not replace validation of that policy.

How the Mediator Restructures Communication

The GoF structure assigns distinct responsibilities to four roles:

Without a mediator, one colleague may depend on several concrete peers. With one, each colleague depends primarily on the mediator-facing contract. The concrete mediator may still be coupled to colleague roles, but that knowledge is not repeated throughout the collaboration. Dependencies are reorganized, not eliminated.

A mediator does more than route messages. Unlike a general message broker, a traffic mediator understands collaboration policy, including which phases follow a pedestrian request and whether a transition is safe.

Forms and Dialogs as Mediators

User interfaces often exhibit the same problem on a smaller scale. A dialog might contain a text field, list, checkbox, validation message, and submit button. If the button knows every field class, or if each control directly enables and disables its peers, the controls become tied to one particular form. Adding a field can require modifications throughout the interface.

A form controller, presenter, view model, or dialog can receive control events, validate the combined state, and update relevant controls. It can implement the cross-control rule, "Enable Submit only when all required fields are valid." Controls retain local presentation behavior, while the mediator owns rules spanning multiple controls.

Not every form implements GoF Mediator. The pattern applies when the form deliberately encapsulates nontrivial collaboration among peer controls.

Benefits of Centralized Interaction Policy

A well-bounded mediator can improve a collaboration in several ways:

These benefits concern interaction responsibility, not guaranteed scalability or performance. The concrete mediator still knows the colleague roles and should coordinate one cohesive collaboration.

When the Mediator Becomes Too Powerful

Centralizing interaction rules creates a concentration of responsibility. If every system rule enters the mediator, it can become a large, low-cohesion god object. A simple-looking colleague method may also trigger extensive behavior that is hidden at its call site.

A synchronous mediator can become a performance bottleneck when it processes high-frequency communication. It can also become a single coordination point whose failure stops the entire collaboration. The mediator must define what happens when a colleague rejects a request, times out, throws an exception, or disappears during a workflow. Lifecycle management is essential so that obsolete colleagues are not retained or invoked after they are no longer valid.

Concurrency adds ordering, synchronization, cancellation, and reentrancy questions. Simultaneous events require priority and rollback rules. Centralization exposes these questions but does not answer them automatically. Simpler colleagues may therefore be balanced by extensive mediator scenario tests.

Keep each mediator bounded by one cohesive collaboration. An intersection mediator may coordinate signal phases, while separate services handle hardware diagnostics, network telemetry, long-term analytics, and citywide route optimization. This boundary prevents unrelated responsibilities from accumulating in the same coordinator.

Mediator Compared with Observer and Facade

Mediator coordinates interactions among peer colleagues and commonly contains collaboration policy. Observer establishes one-to-many notification so dependents can react to changes in a subject. Facade provides a simpler entry point to a subsystem, but it does not normally coordinate an ongoing peer-to-peer workflow. Command represents a request as an object and can be used with Mediator when requests need queuing, logging, retrying, or undo.

Patterns can be combined. Traffic controls might publish hardware status through Observer while a mediator applies phase-transition policy. Commands can represent queued phase requests, and a facade can expose an administrative interface. The pattern name follows the responsibility being addressed.

Deciding When to Use Mediator

Use Mediator when several objects participate in a cohesive workflow, direct references have created a difficult many-to-many dependency network, and moving the interaction rules into one bounded coordinator makes the design easier to understand and change. The mediator should express a clear collaboration policy, while colleagues retain their local behavior.

Do not introduce Mediator merely because two objects communicate or because centralized control sounds orderly. For a simple, stable collaboration, direct communication may be clearer and less expensive. The goal is not centralization for its own sake. The goal is a more coherent allocation of interaction responsibility without transferring so much behavior to the mediator that it becomes a new design problem.


SEMrush Software 9 SEMrush Banner 9