Design patterns: Mediator
The Mediator Pattern is a behavioral design pattern that defines an object (the mediator) responsible for controlling communication among a set of objects. Instead of letting the objects communicate directly with each other, the mediator centralizes and manages their interaction, thereby reducing their coupling.
When to Use It:
- When you have many objects interacting with each other and you want to avoid direct, complex dependencies between them.
- When you want to simplify communication between the objects in a system and make the code more manageable.
Strengths
- Reduces Coupling: Objects don’t communicate directly with each other but through the mediator, reducing dependencies and simplifying the relationships between components.
- Easier Maintenance: With fewer direct dependencies between objects, it’s easier to change the behavior of a single component without affecting other objects.
- Centralized Communication Logic: The communication logic is centralized in the mediator, making it easy to manage interactions among multiple objects.
- Increased Flexibility: It lets you change how objects interact by modifying the mediator, without touching the individual objects.
- Supports Problem Decomposition: It lets you break a complex system down into simpler parts, making the overall architecture clearer and easier to understand.
Use Case
Imagine a chat system in which several users communicate with each other. Instead of letting users send messages directly to one another, a ChatRoom object acts as a centralized mediator.
PHP Code
// Interface for the Mediator
interface ChatRoomMediator {
public function showMessage(User $user, $message);
}
// Concrete Mediator
class ChatRoom implements ChatRoomMediator {
public function showMessage(User $user, $message) {
$time = date('Y-m-d H:i:s');
$sender = $user->getName();
echo "{$time} [{$sender}]: {$message}\n";
}
}
// User class
class User {
private $name;
private $mediator;
public function __construct($name, ChatRoomMediator $mediator) {
$this->name = $name;
$this->mediator = $mediator;
}
public function getName() {
return $this->name;
}
public function sendMessage($message) {
$this->mediator->showMessage($this, $message);
}
}
// Using the Mediator
$mediator = new ChatRoom();
$user1 = new User("Alice", $mediator);
$user2 = new User("Bob", $mediator);
$user1->sendMessage("Hi Bob!");
$user2->sendMessage("Hi Alice! How are you?");
/* output
2024-09-28 12:34:56 [Alice]: Hi Bob!
2024-09-28 12:35:00 [Bob]: Hi Alice! How are you?
*/
Explanation
- ChatRoomMediator is the interface that defines the communication method.
- ChatRoom is the concrete implementation of the mediator, which centralizes the communication logic.
- User represents the objects taking part in the chat. Users don’t communicate directly with each other; they send messages through the mediator (ChatRoom).
- The ChatRoom mediator handles the delivery of messages between users, reducing the coupling between them.