Mediator
Defines an object that encapsulates how objects interact.
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
- • 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
- • 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
How It Works
Direct Communication
Objects communicate directly - complex dependencies.
Basic Implementation
Chat room as a mediator between users:
Real-World Example: Dialog Components
UI dialog mediating between form components: