Behavioral

Mediator

Defines an object that encapsulates how objects interact.

Chat roomsAir traffic controlGUI components

Understanding Mediator

The Mediator pattern defines an object that encapsulates how a set of objects interact, promoting loose coupling by preventing objects from referring to each other directly. Instead, all communication goes through the mediator, which coordinates the interaction. In Go, the mediator is an interface or struct that all participants (colleagues) reference, and it routes messages or events between them. This is commonly used in chat room systems, air traffic control simulations, and GUI component coordination where multiple objects need to interact without creating a tangled web of direct dependencies.

Key Concepts

  • Mediator — central hub that coordinates communication between colleague objects
  • Colleagues — objects that interact through the mediator rather than directly with each other
  • Reduced coupling — colleagues only know the mediator interface, not other colleague types
  • Centralized logic — interaction rules live in one place (the mediator) rather than scattered across objects

When to Use

✅ Use when
  • • Multiple objects communicate in complex ways, creating a tangled dependency graph
  • • You want to centralize communication control (chat rooms, event dispatchers)
  • • Reusing individual components is hard because they depend on many others
  • • You need to change interaction behavior without modifying the participants
⚠️ Avoid when
  • • The mediator becomes a "god object" managing too much logic
  • • Simple direct communication between 2-3 objects is clearer
  • • Observer/Pub-Sub pattern is a better fit for broadcast-style communication

Structure

Colleague A / Colleague B / Colleague C
↓ send/receive via
Mediator (routes messages)
↓ coordinates
All Interactions

How It Works

A
B
C
D
M
⚠ Complex direct dependencies
1

Direct Communication

Objects communicate directly - complex dependencies.

1 / 4

Basic Implementation

Chat room as a mediator between users:

main.go
Loading editor...

Real-World Example: Dialog Components

UI dialog mediating between form components:

main.go
Loading editor...