🧩 Mediator Pattern
✅ Intent
- Enable components to communicate through a mediator instead of referencing each other directly
- Centralize the relationships to make interactions easier to manage
✅ Motivation
- Useful when you want a central coordinating class to manage multiple components
- Allows components to remain independent while still interacting
✅ When to Use
- When you need to manage relationships between multiple components (e.g., UI, forms, or services)
- When you want to make control flow and coordination more visible and manageable
✅ Code Example
- TypeScript
- PHP
- Python
// Mediator インターフェース
interface Mediator {
notify(sender: string, data: any): void;
}
// コンポーネント(UserService)
class UserService {
constructor(private mediator: Mediator) {}
registerUser(email: string): void {
console.log(`ユーザー登録: ${email}`);
this.mediator.notify("UserService", email);
}
}
// コンポーネント(Mailer)
class Mailer {
sendWelcome(email: string): void {
console.log(`送信しました: ${email} → ようこそ!`);
}
}
// Mediator 実装
class AppMediator implements Mediator {
constructor(private mailer: Mailer) {}
notify(sender: string, data: any): void {
if (sender === "UserService") {
this.mailer.sendWelcome(data);
}
}
}
// 利用例
const mailer = new Mailer();
const mediator = new AppMediator(mailer);
const userService = new UserService(mediator);
userService.registerUser("user@example.com");
<?php
interface Mediator {
public function notify(string $sender, mixed $data): void;
}
class UserService {
public function __construct(private Mediator $mediator) {}
public function registerUser(string $email): void {
echo "ユーザー登録: {$email}\n";
$this->mediator->notify("UserService", $email);
}
}
class Mailer {
public function sendWelcome(string $email): void {
echo "送信しました: {$email} → ようこそ!\n";
}
}
class AppMediator implements Mediator {
public function __construct(private Mailer $mailer) {}
public function notify(string $sender, mixed $data): void {
if ($sender === "UserService") {
$this->mailer->sendWelcome($data);
}
}
}
// 利用例
$mailer = new Mailer();
$mediator = new AppMediator($mailer);
$userService = new UserService($mediator);
$userService->registerUser("user@example.com");
from abc import ABC, abstractmethod
class Mediator(ABC):
@abstractmethod
def notify(self, sender: str, data: any):
pass
class Mailer:
def send_welcome(self, email: str):
print(f"送信しました: {email} → ようこそ!")
class AppMediator(Mediator):
def __init__(self, mailer: Mailer):
self.mailer = mailer
def notify(self, sender: str, data: any):
if sender == "UserService":
self.mailer.send_welcome(data)
class UserService:
def __init__(self, mediator: Mediator):
self.mediator = mediator
def register_user(self, email: str):
print(f"ユーザー登録: {email}")
self.mediator.notify("UserService", email)
# 利用例
mailer = Mailer()
mediator = AppMediator(mailer)
user_service = UserService(mediator)
user_service.register_user("user@example.com")
✅ Explanation
This code applies the Mediator
pattern to remove direct dependencies between components (UserService
and Mailer
)
and enables communication through a centralized Mediator
.
The Mediator
pattern delegates communication between objects to a central mediator,
thus reducing coupling between components.
1. Overview of the Mediator Pattern
-
Mediator: Interface for mediating communication between components
- Represented by
Mediator
- Represented by
-
ConcreteMediator: Implements the
Mediator
interface and contains the logic to coordinate components- Represented by
AppMediator
- Represented by
-
Colleague: Components that interact through the mediator
- Represented by
UserService
andMailer
- Represented by
2. Key Classes and Their Roles
-
Mediator
- Interface for coordinating component communication
- Declares
notify(sender: string, data: any): void
-
AppMediator
- Concrete implementation of
Mediator
- Handles communication logic in
notify
, routing messages fromUserService
toMailer
- Concrete implementation of
-
UserService
- A colleague component
- Performs user registration and notifies the mediator of events
-
Mailer
- Another colleague component
- Receives notification from the mediator and sends emails
3. UML Class Diagram
4. Benefits of the Mediator Pattern
- Loose Coupling: Eliminates direct dependencies between components, reducing complexity
- Extensibility: New components can be integrated by simply updating the
Mediator
- Centralized Coordination: Interaction logic is centralized, improving readability and maintainability
This design is highly effective when multiple components need to communicate,
while preserving modularity and scalability of the codebase.