BehavioralPythonverifiedVerified

Mediator Pattern in Python

Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.

How to Implement the Mediator Pattern in Python

1Step 1: Define the Mediator interface and participant base class

from __future__ import annotations
from typing import Protocol


class Mediator(Protocol):
    def notify(self, sender: "ChatParticipant", message: str) -> None: ...


class ChatParticipant:
    def __init__(self, name: str, mediator: Mediator) -> None:
        self.name = name
        self._mediator = mediator

    def send(self, message: str) -> None:
        print(f"[{self.name}] sends: {message}")
        self._mediator.notify(self, message)

    def receive(self, from_name: str, message: str) -> None:
        print(f"[{self.name}] received from {from_name}: {message}")

2Step 2: Implement the ChatRoom as a concrete mediator

class ChatRoom:
    def __init__(self) -> None:
        self._participants: list[ChatParticipant] = []

    def join(self, participant: ChatParticipant) -> None:
        self._participants.append(participant)

    def notify(self, sender: ChatParticipant, message: str) -> None:
        for participant in self._participants:
            if participant is not sender:
                participant.receive(sender.name, message)

3Step 3: Connect participants and exchange messages

room = ChatRoom()
alice = ChatParticipant("Alice", room)
bob = ChatParticipant("Bob", room)
carol = ChatParticipant("Carol", room)

room.join(alice)
room.join(bob)
room.join(carol)

alice.send("Hello everyone!")

Mediator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mediator Pattern in the Real World

An air traffic control tower is the classic example. Instead of every plane communicating directly with every other plane—a chaotic and dangerous mess—all aircraft talk only to the control tower. The tower mediates all interactions, directing each plane based on the overall picture it maintains. Planes are decoupled from each other entirely.