Objects That Stop Talking to Each Other: The Mediator Pattern in Python

This article explains how the Mediator pattern gathers the rules of an interaction in one object, how a dialog coordinates its widgets through it, how it differs from Observer and Facade, and how to avoid god mediators and feedback loops.

A green tree python coiled in neat loops over a branch, its head resting on top of the coils against a soft grey background
Photo by Giulio Gabrieli on Unsplash

When several objects must react to one another, the simplest code lets each of them refer to the others directly, so that a form field enables a button, the button reads three fields and a checkbox hides one of them. Every new object then adds references in both directions, and the rules of the interaction end up scattered across all the classes involved. The present article examines the Mediator pattern, which places those rules in one object, the mediator, and lets the other objects, the colleagues, communicate only through it. A raid in an online game provides an appropriate image: twenty players do not negotiate with one another who attacks and who heals; each reports to the raid leader, who knows the whole situation and assigns the next action to each of them. This means that each colleague reports what happened to it and receives instructions, while only the mediator knows which colleague must react to which event. The analogy, however, stops at this point, because a raid leader improvises with judgement, whereas a mediator applies only the rules written in its code, and every missing rule is a missing reaction. Gathering the rules of an interaction in one place, so that the objects involved no longer know one another, is the secret weapon of this pattern.

A Dialog That Coordinates Its Widgets

Dialog boxes are the classic case for the pattern, because their widgets depend on one another in both directions. In the following example, a sign-up dialog creates its widgets and receives their notifications; a checkbox for business accounts shows the field for the company name, and the submit button is enabled only when the e-mail address is plausible and, for business accounts, the company name is present. Events are members of an Enum, so a misspelt event raises an AttributeError instead of being silently ignored.

from enum import Enum

class Event(Enum):
    CHANGED = "changed"
    CLICKED = "clicked"

class Widget:
    def __init__(self, dialog):
        self.dialog, self.enabled, self.visible = dialog, True, True

class TextField(Widget):
    def __init__(self, dialog):
        super().__init__(dialog)
        self.text = ""

    def type_text(self, text):
        self.text = text
        self.dialog.notify(self, Event.CHANGED)

class Checkbox(Widget):
    def __init__(self, dialog):
        super().__init__(dialog)
        self.checked = False

    def toggle(self):
        self.checked = not self.checked
        self.dialog.notify(self, Event.CHANGED)

class Button(Widget):
    def click(self):
        if self.enabled:
            self.dialog.notify(self, Event.CLICKED)

class SignupDialog:
    def __init__(self):
        self.submitted = None
        self.email, self.business = TextField(self), Checkbox(self)
        self.company, self.submit = TextField(self), Button(self)
        self._update()

    def notify(self, sender, event):
        if event is Event.CLICKED and sender is self.submit:
            self.submitted = {"email": self.email.text, "company": self.company.text or None}
        else:
            self._update()

    def _update(self):
        self.company.visible = self.business.checked
        email_ok = "@" in self.email.text
        company_ok = not self.business.checked or bool(self.company.text)
        self.submit.enabled = email_ok and company_ok

dialog = SignupDialog()
print(dialog.submit.enabled, dialog.company.visible)  # Output: False False
dialog.email.type_text("[email protected]")
print(dialog.submit.enabled)                          # Output: True
dialog.business.toggle()
print(dialog.submit.enabled, dialog.company.visible)  # Output: False True
dialog.company.type_text("Analytical Engines Ltd")
dialog.submit.click()
print(dialog.submitted)  # Output: {'email': '[email protected]', 'company': 'Analytical Engines Ltd'}

None of the widgets refers to another: the text field and the checkbox only report that they changed, and the button only reports that it was clicked. Every rule of the form, which field is visible and when the button is enabled, is written in _update, so changing a rule means editing one method, and the widget classes can be reused in any other dialog.

Mediator and Observer

The Mediator pattern is often confused with the Observer pattern, examined in the article devoted to the Observer pattern, because both deliver notifications. An observer subscription is one-to-many and has no logic of its own: the subject announces a change, and every subscriber decides independently what to do. A mediator holds the logic of the interaction: it receives an event, reads the state of several colleagues and decides which of them must change, as the dialog decides the state of the button from three widgets. The two are frequently combined, since a mediator may subscribe to its colleagues as an observer. The pattern also differs from a facade, as described in the article devoted to the Facade pattern: the subsystems behind a facade do not know it exists, whereas colleagues hold a reference to their mediator and report to it.

Pitfalls of the Mediator Pattern

A mediator gathers the rules that were scattered among its colleagues, so its errors come from gathering too much or from reactions that trigger further reactions. Six pitfalls are distinguished, which are the following:

  1. The god mediator. A mediator that coordinates every object of an application becomes the most complex and most coupled class of the program; one mediator per dialog, screen or workflow keeps each one small.
  2. Feedback loops. A change made by the mediator may cause a colleague to notify the mediator again, which then makes the same change, until Python raises RecursionError.
  3. Events as strings. A misspelt event name is not an error; it is simply never handled.
  4. Colleagues that bypass the mediator. A colleague that reaches another colleague directly reintroduces the coupling that the pattern removed.
  5. Unused sender information. A mediator that ignores which colleague sent an event must recompute everything on every notification, which hides the cause of each change.
  6. A mediator for two objects. Two objects that interact in one way need a direct call, not an intermediary.

The second pitfall is reproduced in the following example, in which a converter keeps a field in degrees Celsius and a field in degrees Fahrenheit synchronized.

class Field:
    def __init__(self, mediator):
        self.value, self.mediator = 0.0, mediator

    def set(self, value):
        self.value = value
        self.mediator.changed(self)

class NaiveConverter:
    def __init__(self):
        self.celsius, self.fahrenheit = Field(self), Field(self)

    def changed(self, sender):
        if sender is self.celsius:
            self.fahrenheit.set(self.celsius.value * 9 / 5 + 32)
        else:
            self.celsius.set((self.fahrenheit.value - 32) * 5 / 9)

class GuardedConverter(NaiveConverter):
    def __init__(self):
        super().__init__()
        self._updating = False

    def changed(self, sender):
        if self._updating:
            return
        self._updating = True
        try:
            super().changed(sender)
        finally:
            self._updating = False

try:
    NaiveConverter().celsius.set(100)
except RecursionError:
    print("RecursionError")  # Output: RecursionError

converter = GuardedConverter()
converter.celsius.set(100)
print(converter.fahrenheit.value)  # Output: 212.0
converter.fahrenheit.set(32)
print(converter.celsius.value)     # Output: 0.0

In the naive converter, setting the Fahrenheit field notifies the mediator, which sets the Celsius field, which notifies the mediator again, without end. The guarded converter ignores notifications that arrive while it is already updating, and the finally clause resets the flag even if a conversion raises an exception.

Choosing How Objects Communicate

Consequently, the mediator is justified when several objects interact according to rules that involve more than one of them, as the following table summarizes.

Situation Recommended approach
Two objects with a single interaction A direct method call
One source, many independent listeners The Observer pattern
Several objects whose reactions depend on one another's state A mediator
A simple entry point to a subsystem A facade
Synchronized values that update each other A mediator with a re-entrancy guard
A large application with many screens One mediator per screen or workflow

Conclusion

It is concluded that the Mediator pattern moves the rules of an interaction from the objects involved into one coordinating object, so that colleagues report events and receive instructions without knowing one another, and that it differs from the Observer pattern by holding the logic that decides who reacts. This magic depends on keeping each mediator limited to one interaction, on naming events with enumerations and on guarding against notifications that trigger themselves. Making every instance of a class share one state, while each remains a separate object, is the purpose of the Monostate pattern, also known as Borg, which is developed in a future article of this series.