Python Design Patterns

Mediator Pattern in Python

Mediator reduces dependencies among colleagues by routing their interactions through one coordinator.

What is Mediator Pattern?

Mediator reduces dependencies among colleagues by routing their interactions through one coordinator.

Centralize communication between objects that would otherwise reference each other directly.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

Example code

Run code →
main.py
class ChatRoom:
    # Mediator: route colleague communication through a coordinator.
    def send(self, sender, recipient, message):
        # Coordinate communication between colleague objects.
        recipient.receive(sender.name, message)


class User:
    def __init__(self, name, room): self.name, self.room = name, room
    def send(self, recipient, message): self.room.send(self, recipient, message)
    def receive(self, sender, message): print(f"{self.name} from {sender}: {message}")


room = ChatRoom()
ada, lin = User("Ada", room), User("Lin", room)
ada.send(lin, "Hello")

Expected output

Lin from Ada: Hello

How it works

ChatRoom delivers messages between users so User objects remain unaware of one another.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in Python IDE →