Mediator Pattern¶
Category: Behavioral Pattern
Overview¶
Define an object that encapsulates how a set of objects interact. This pattern promotes loose coupling by keeping objects from referring to each other explicitly and lets you vary their interaction independently by centralizing complex communications and control logic.
Usage Guidelines¶
Use when:
- Many objects communicate in complex ways
- Want to centralize communication logic
- Objects shouldn't depend on each other directly
- Want to reuse objects in different contexts
Avoid when:
- Objects have simple, straightforward interactions
- Mediator indirection is unacceptable for performance
- Mediator becomes too complex (God object)
- Direct communication is clearer and simpler
Implementation¶
from __future__ import annotations
from abc import ABC, abstractmethod
class Mediator(ABC):
"""Abstract mediator interface."""
@abstractmethod
def send_message(self, message: str, sender: Colleague) -> None:
"""Send a message through the mediator."""
pass
class Colleague(ABC):
"""Abstract colleague that communicates through mediator."""
def __init__(self, mediator: Mediator) -> None:
"""Initialize colleague with a mediator."""
self.mediator = mediator
@abstractmethod
def receive(self, message: str) -> None:
"""Receive a message from the mediator."""
pass
@abstractmethod
def send(self, message: str) -> None:
"""Send a message through the mediator."""
pass
class ChatRoom(Mediator):
"""Concrete mediator implementing a chat room."""
def __init__(self) -> None:
"""Initialize chat room."""
self.users: list[User] = []
def register_user(self, user: User) -> None:
"""Register a user in the chat room."""
if user not in self.users:
self.users.append(user)
def send_message(self, message: str, sender: Colleague) -> None:
"""Send message to all users except sender."""
for user in self.users:
if user != sender:
user.receive(message)
class User(Colleague):
"""Concrete colleague representing a chat user."""
def __init__(self, name: str, chatroom: ChatRoom) -> None:
"""Initialize user."""
super().__init__(chatroom)
self.name = name
self.messages: list[str] = []
chatroom.register_user(self)
def receive(self, message: str) -> None:
"""Receive a message."""
self.messages.append(f"Received: {message}")
def send(self, message: str) -> None:
"""Send a message."""
self.messages.append(f"Sent: {message}")
self.mediator.send_message(message, self)
def get_messages(self) -> list[str]:
"""Get all messages for this user."""
return self.messages
Usage¶
# Chat room
chatroom = ChatRoom()
alice = User("Alice", chatroom)
bob = User("Bob", chatroom)
charlie = User("Charlie", chatroom)
alice.send("Hello everyone!")
# Bob and Charlie receive the message
bob.send("Hi Alice!")
# Alice and Charlie receive the message
print(alice.get_messages())
print(bob.get_messages())
Trade-offs¶
Benefits:
- Loose coupling with colleagues not referencing each other directly
- Centralized control of communication logic in one place
- Simplified objects as mediator handles complexity
- Colleagues can be reused with different mediators
Drawbacks:
- Mediator can become too complex and hard to maintain (God object)
- Single point of failure as mediator failure affects all colleagues
- Indirect communication can make debugging harder
- Mediator adds indirection overhead for performance
Real-World Examples¶
- GUI frameworks with dialog boxes coordinating widgets
- Chat applications with chat rooms mediating communications
- Air traffic control coordinating aircraft
- MVC controllers coordinating models and views
Related Patterns¶
- Observer
- Facade
- Command
API Reference¶
design_patterns.behavioral.mediator
¶
Mediator Pattern Module
The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly and lets you vary their interaction independently. The mediator centralizes complex communications and control logic between related objects.
Example
Chat room where users communicate through mediator:
AirTrafficControl
¶
Bases: Mediator
Mediator for coordinating aircraft.
Source code in src/design_patterns/behavioral/mediator.py
__init__()
¶
register_aircraft(aircraft)
¶
Register an aircraft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aircraft
|
Aircraft
|
Aircraft to register. |
required |
request_landing(aircraft)
¶
Handle landing request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aircraft
|
Aircraft
|
Aircraft requesting landing. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Landing permission status. |
Source code in src/design_patterns/behavioral/mediator.py
Aircraft
¶
Bases: Colleague
Concrete colleague representing an aircraft.
Source code in src/design_patterns/behavioral/mediator.py
__init__(call_sign, atc)
¶
Initialize aircraft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call_sign
|
str
|
Aircraft call sign. |
required |
atc
|
AirTrafficControl
|
Air traffic control mediator. |
required |
Source code in src/design_patterns/behavioral/mediator.py
receive(message)
¶
Receive a message from ATC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message received. |
required |
request_landing()
¶
Request landing permission.
Returns:
| Type | Description |
|---|---|
str
|
Landing permission response. |
Source code in src/design_patterns/behavioral/mediator.py
send(message)
¶
Send a message to ATC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message to send. |
required |
Source code in src/design_patterns/behavioral/mediator.py
ChatRoom
¶
Bases: Mediator
Concrete mediator implementing a chat room.
Source code in src/design_patterns/behavioral/mediator.py
__init__()
¶
register_user(user)
¶
Register a user in the chat room.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user
|
User
|
User to register. |
required |
Colleague
¶
Bases: ABC
Abstract colleague that communicates through mediator.
Source code in src/design_patterns/behavioral/mediator.py
__init__(mediator)
¶
Initialize colleague with a mediator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mediator
|
Mediator
|
The mediator to use for communication. |
required |
receive(message)
abstractmethod
¶
Receive a message from the mediator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message received. |
required |
send(message)
abstractmethod
¶
Send a message through the mediator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message to send. |
required |
Mediator
¶
Bases: ABC
Abstract mediator interface.
Source code in src/design_patterns/behavioral/mediator.py
SmartDevice
¶
Bases: Colleague
Concrete colleague representing a smart home device.
Source code in src/design_patterns/behavioral/mediator.py
__init__(name, smart_home)
¶
Initialize smart device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Device name. |
required |
smart_home
|
SmartHome
|
Smart home mediator. |
required |
Source code in src/design_patterns/behavioral/mediator.py
receive(message)
¶
Receive command from smart home.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Command received. |
required |
Source code in src/design_patterns/behavioral/mediator.py
send(message)
¶
Send event to smart home.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Event message. |
required |
trigger_event(event)
¶
Trigger an event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
str
|
Event description. |
required |
SmartHome
¶
Bases: Mediator
Mediator for smart home devices.
Source code in src/design_patterns/behavioral/mediator.py
__init__()
¶
register_device(device)
¶
Register a smart device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
SmartDevice
|
Device to register. |
required |
send_message(message, sender)
¶
Process device event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Event message. |
required |
sender
|
Colleague
|
Device sending the event. |
required |
Source code in src/design_patterns/behavioral/mediator.py
User
¶
Bases: Colleague
Concrete colleague representing a chat user.
Source code in src/design_patterns/behavioral/mediator.py
__init__(name, chatroom)
¶
Initialize user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
User name. |
required |
chatroom
|
ChatRoom
|
Chat room mediator. |
required |
Source code in src/design_patterns/behavioral/mediator.py
get_messages()
¶
receive(message)
¶
Receive a message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message received. |
required |
send(message)
¶
Send a message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Message to send. |
required |