The Problem
UI components or domain objects often need to react to each other. If every component directly references every other one, dependencies become tangled and small changes ripple across the whole group. The collaboration becomes hard to reason about because there is no single place that describes the conversation.
The Solution
Mediator moves coordination into a dedicated object. In Go, participants hold a mediator interface rather than references to each peer. The mediator receives events from a component, decides how the rest of the group should react, and keeps the coordination rules centralized.
Structure
- Mediator interface: Defines the notification channel components use.
- Concrete mediator:
CheckoutCoordinatorowns the collaboration rules. - Colleagues: Payment, shipping, and summary components report state changes to the mediator.
- Client: Wires components to the coordinator during setup.
Implementation
This example coordinates a checkout form. When shipping or payment changes, the mediator recalculates which parts should be enabled and what the summary panel should show.
package main
type CheckoutMediator interface {
Notify(sender string, event string)
} Best Practices
- Use Mediator when many peer-to-peer references are making a collaboration hard to follow.
- Keep colleagues dumb about each other. They should only know the mediator contract.
- Do not let the mediator become a god object; split it when several unrelated conversations emerge.
- Keep mediator events explicit and domain-shaped so the coordination is readable.
- If you only need publish/subscribe notifications, Observer may be a better fit than a central coordinator.
When to Use
- Several objects collaborate tightly and direct references create a web of coupling.
- You want one place to own coordination rules for a bounded interaction.
- Participants should stay reusable outside of one particular collaboration group.
When NOT to Use
- Only one object triggers another and the collaboration is already simple.
- A mediator would just centralize trivial method forwarding.
- The coordinator would absorb too many unrelated workflows.