Design patterns: Mediator

date: · 3 min
author: Mauto
series: Design Patterns/ part 18/24

The classic Gang of Four patterns, one per part, with practical PHP examples.

  1. Design Patterns
  2. Design patterns: Singleton
  3. Design patterns: Factory Method
  4. Design patterns: Abstract Factory
  5. Design patterns: Builder
  6. Design patterns: Prototype
  7. Design patterns: Adapter
  8. Bridge Pattern in PHP: What It Is, When to Use It, with Examples
  9. Design patterns: Composite
  10. Design patterns: Decorator
  11. Design patterns: Facade, What It Is and How to Use It (PHP)
  12. Design patterns: Flyweight
  13. Design patterns: Proxy
  14. Design patterns: Chain of Responsibility Explained (PHP)
  15. Design patterns: Command
  16. Design patterns: Interpreter
  17. Design patterns: Iterator
  18. Design patterns: Mediator
  19. Design patterns: Memento
  20. Design patterns: Observer
  21. Design patterns: State, What It Is and How to Use It (PHP)
  22. Design patterns: Strategy
  23. Design patterns: Template Method
  24. Design patterns: Visitor
the whole guide >

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

  1. Reduces Coupling: Objects don’t communicate directly with each other but through the mediator, reducing dependencies and simplifying the relationships between components.
  2. Easier Maintenance: With fewer direct dependencies between objects, it’s easier to change the behavior of a single component without affecting other objects.
  3. Centralized Communication Logic: The communication logic is centralized in the mediator, making it easy to manage interactions among multiple objects.
  4. Increased Flexibility: It lets you change how objects interact by modifying the mediator, without touching the individual objects.
  5. 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 register(User $user);
    public function showMessage(User $sender, $message);
}

// Concrete Mediator
class ChatRoom implements ChatRoomMediator {
    private $users = [];

    public function register(User $user) {
        $this->users[] = $user;
    }

    // Delivers the message to every registered user except the sender
    public function showMessage(User $sender, $message) {
        foreach ($this->users as $user) {
            if ($user !== $sender) {
                $user->receive($sender->getName(), $message);
            }
        }
    }
}

// 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);
    }

    public function receive($senderName, $message) {
        echo "{$this->name} receives from {$senderName}: {$message}\n";
    }
}

// Using the Mediator
$mediator = new ChatRoom();

$user1 = new User("Alice", $mediator);
$user2 = new User("Bob", $mediator);
$user3 = new User("Charlie", $mediator);

$mediator->register($user1);
$mediator->register($user2);
$mediator->register($user3);

$user1->sendMessage("Hi everyone!");
$user2->sendMessage("Hi Alice! How are you?");

/* output
Bob receives from Alice: Hi everyone!
Charlie receives from Alice: Hi everyone!
Alice receives from Bob: Hi Alice! How are you?
Charlie receives from Bob: Hi Alice! How are you?
*/

Explanation

  • ChatRoomMediator is the interface that defines the methods for registering users (register()) and forwarding messages (showMessage()).
  • ChatRoom is the concrete implementation of the mediator: it keeps the list of registered users and delivers each message to all the others, centralizing 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) and receive them with the receive() method.
  • The ChatRoom mediator handles the delivery of messages between users, reducing the coupling between them.

BACK TO THE GUIDE

Copied