Mediator
Intent
Route all communication between peers through one hub object so peers never reference each other directly.
Motivation
A chat room has users who message each other. If every user holds a pointer to every other user, adding, removing, or muting someone touches the whole mesh. A room hub that receives each message and forwards it to the right recipient collapses that mesh into spokes: users know the room, the room knows the users.
Structure
flowchart LR Alice[Alice User] --> Room[Chat Room Mediator] Bob[Bob User] --> Room Room --> Alice Room --> Bob
- Colleagues (Alice, Bob) — send and receive through the mediator; hold no peer references.
- Mediator (Chat Room) — owns the directory and the routing rules; delivers each message.
Consequences
- Benefit: peers stay simple and swappable; routing, muting, and logging rules live in one auditable place.
- Cost: the hub can grow into a god object if every rule piles in — split routing from policy when it swells.
Basic Recap
Mediator centralizes interactions among a set of colleagues so they communicate through a coordinator rather than holding references to one another. Each colleague focuses on its own capability and reports relevant events or requests. The mediator decides how capabilities collaborate for a shared workflow. This reduces a mesh of dependencies, but it also concentrates workflow knowledge that must be kept explicit and testable.
Complex Scenario
An order fulfillment coordinator mediates inventory, payment, shipment, and customer-notification components. Inventory reports reservation results to the mediator, which decides when payment capture can proceed and when shipment instructions are allowed. Components do not call one another directly or infer the overall order state. The mediator records workflow progress and emits notifications only after meaningful fulfillment transitions.
Edge cases
- Partial failure: Payment may succeed after inventory reserved but before shipment creation fails; the mediator needs a durable recovery path and a compensation decision instead of simply returning an exception.
- Retries: Redelivered colleague events must be deduplicated by event and order identifiers so payment capture and notifications happen once logically.
- Concurrency: Reservation and cancellation events can arrive concurrently; order versioning or serialized processing prevents the mediator from acting on an obsolete state.
The mediator should coordinate domain transitions, while colleagues retain the rules and technical details of their own operations.
Sketch (illustrative pseudocode, not runnable):
FulfillmentMediator.on(event):
if eventJournal.alreadyHandled(event.id):
return
order = orders.lockAndLoad(event.orderId)
transition = workflow.decide(order, event)
for action in transition.actions:
actionJournal.dispatchOnce(action.key, action)
orders.saveWithVersion(order, transition.newVersion)
eventJournal.markHandled(event.id)
Inventory.onReserved(result):
mediator.on(InventoryReserved(result.orderId, result.lines))
When to Use / When Not to Use
Use when:
- A mesh of peers manages each other directly and changes ripple everywhere.
- Routing rules (who hears what) deserve one visible owner.
Avoid when:
- Only two peers talk on a fixed path — a direct call is clearer than a hub.
Examples
examples/elixir/mediator/examples/dart/mediator/examples/go/mediator/examples/rust/mediator/
Expected outcome: Alice and Bob exchange two messages, each routed visibly through the room.
Anti-pattern / Failure Mode
-
Misuse: A mediator that becomes the god object holding all peer logic.
-
Review signal: Peers that can only be tested through the full mediator mesh.
-
Misuse symptom: The mediator absorbs validation, pricing, database access, vendor protocols, and every new feature until colleagues are anemic wrappers. Direct colleague calls then reappear for exceptions, producing both a god mediator and the original tangled mesh.
-
Review signal: Watch for a mediator with many unrelated event types, mutable workflow state not persisted across restarts, and colleagues importing one another’s implementation classes. Tests should replay duplicate and out-of-order events; dashboards need durable workflow steps rather than one opaque
processOrderduration.
Related
- Observer — hub routing vs broadcasts.
- Facade — peers through a hub vs one call for a subsystem.
- Chat Router — mediator screening with reversible moderation.
Exercise
Add a third user plus a mute rule: messages from muted senders never deliver. Keep all routing logic inside the room — users must not check mute lists themselves.
Self-check
- What do colleagues know about each other?
Answer
Nothing — each colleague only knows the mediator, which resolves recipients. - Where does a mute rule live?
Answer
In the mediator, so policy changes touch one hub instead of every user. - Mediator vs Observer: what differs?
Answer
Observer broadcasts one-to-many with no routing logic; Mediator peers talk many-to-many and the hub decides who gets what.