Programming Search⌘K

Patterncore

Mediator pattern

Also called Mediator, director, coordinator, controller of a form.

Put the rules that join a group of objects into one object, the mediator. The objects in the group talk only to the mediator, so none of them needs a reference to the others.

Family
behavioral-design
Intent
Define an object that holds the way a set of objects interact, so that the objects do not refer to each other and the interaction can change on its own.

Intent

Define an object that holds the way a set of objects interact. The objects then do not refer to each other, and the way they interact can change without a change to them.1 Design Patterns calls the objects in the set colleagues. Each colleague knows only the mediator. When something happens to it, it tells the mediator, and the mediator decides what the other colleagues must do.

Problem

Design Patterns starts with a dialog box. A font dialog has a list of fonts, a text field, and buttons. The widgets depend on each other. A choice in the list changes the text in the field. A change in the field can change the choice in the list. Some buttons are enabled only when the field holds text.1

The examples use a checkout form with three widgets: a country selector, a postcode field and a submit button. The rules are these. A change of country clears the postcode, because a postcode from one country is not valid in another, and it disables the submit button. A postcode is valid when its length is the length that the country needs: 5 for the US and 6 for the Netherlands in this example. The submit button is enabled only when the postcode is valid.

The direct design puts each rule in a widget. The country selector holds a reference to the postcode field and to the button, and the postcode field holds a reference to the selector and to the button. With n widgets that is up to n(n-1) references. Each widget then knows the form that it is in, and none of them can go into another form. A rule that joins three widgets is split across three classes, and a reader must open all three to see it.

The forces are these. The widgets must be reusable, so they must not know each other. The rules of one form must be in one place, so that a reader can see them and a change has one place to go. And the rules change more often than the widgets do.

Solution

Design Patterns names three participants.1

  • Mediator defines the interface that colleagues use to talk to it. Often it is one method, such as changed(colleague).
  • ConcreteMediator knows its colleagues, and it holds the rules that join them. Here it is CheckoutForm.
  • Colleague classes each know their mediator. A colleague tells the mediator when its state changes, and it does not talk to other colleagues. Here they are Select, TextField and Button.
             before                                 after

   country <------> postcode               country    postcode    submit
      ^  \          /  ^                       \         |          /
      |   \        /   |                        v        v         v
      |    v      v    |                     CheckoutForm (mediator)
      +---> submit <---+                       all rules are here

The references go from each widget to the mediator, and from the mediator to each widget. The many-to-many links between widgets become one-to-many links between the mediator and the widgets.1

The examples follow one sequence:

  1. The user chooses the US. The form clears the postcode.
  2. The user types 1234. It is too short, so the button stays disabled.
  3. The user types 12345. The form enables the button.
  4. The user chooses the Netherlands. The form clears the postcode and disables the button.
  5. The user types 1234AB, and the form enables the button.
  6. The user clicks the button, and the form sends the order.

Feedback loops

A mediator changes colleagues as a result of a change to a colleague. When each change to a colleague notifies the mediator, the mediator's own changes come back to it as events. Two fields that the mediator keeps equal show the problem. A change to the first sets the second, which notifies the mediator, which sets the first, and so on:

This code raises RecursionError, on purpose.

class Field:
    def __init__(self, name, form):
        self.name, self.form, self.text = name, form, ""

    def set_text(self, text):
        self.text = text
        self.form.changed(self)  # notifies on each set, also when the form sets it


class AddressForm:
    """Keeps the billing address the same as the shipping address."""

    def __init__(self):
        self.shipping = Field("shipping", self)
        self.billing = Field("billing", self)

    def changed(self, field):
        other = self.billing if field is self.shipping else self.shipping
        other.set_text(field.text)


form = AddressForm()
form.shipping.set_text("1 Main Street")
print(form.billing.text)

Python raises RecursionError when the interpreter passes the maximum recursion depth.5 Other languages overflow the stack or loop until the process stops. There are two fixes. A colleague notifies only when its value really changes. Or a colleague tells a change by the user apart from a change by the program, and only the first notifies. With the first fix:

class Field:
    def __init__(self, name, form):
        self.name, self.form, self.text = name, form, ""

    def set_text(self, text):
        if text == self.text:
            return  # no change, so no notification
        self.text = text
        self.form.changed(self)


class AddressForm:
    def __init__(self):
        self.shipping = Field("shipping", self)
        self.billing = Field("billing", self)

    def changed(self, field):
        other = self.billing if field is self.shipping else self.shipping
        other.set_text(field.text)


form = AddressForm()
form.shipping.set_text("1 Main Street")
print(form.billing.text)
Output
1 Main Street

The examples use both fixes. The postcode field has a type method for the user, which notifies, and a set_text method for the mediator, which does not. The button's set_enabled does nothing when the state does not change.

A mediator built on observers

Design Patterns describes two ways for colleagues to tell the mediator about a change. A colleague can call a notification method of the mediator, as in the examples. Or the mediator can be an observer of each colleague.1 In the second form, the colleagues do not know the mediator at all. They raise events, and the mediator subscribes to them. In a browser, each DOM element is an EventTarget, an object to which events are dispatched and which keeps a list of event listeners.4 Node.js has the same class. Here the form observes two password fields:

class Field extends EventTarget {
  #text = "";
  constructor(name) {
    super();
    this.name = name;
  }
  get text() {
    return this.#text;
  }
  type(text) {
    this.#text = text;
    console.log(`${this.name} = "${text}"`);
    this.dispatchEvent(new Event("change")); // the field does not know who listens
  }
}

class Button {
  enabled = false;
  constructor(name) {
    this.name = name;
  }
  setEnabled(enabled) {
    if (enabled !== this.enabled) {
      this.enabled = enabled;
      console.log(`${this.name} ${enabled ? "enabled" : "disabled"}`);
    }
  }
}

// The mediator observes the fields and holds the rule that joins them.
class SignupForm {
  password = new Field("password");
  confirm = new Field("confirm");
  submit = new Button("submit");

  constructor() {
    const check = () => {
      const { text } = this.password;
      this.submit.setEnabled(text.length >= 8 && text === this.confirm.text);
    };
    this.password.addEventListener("change", check);
    this.confirm.addEventListener("change", check);
  }
}

const form = new SignupForm();
form.password.type("correct horse");
form.confirm.type("correct");
form.confirm.type("correct horse");
form.password.type("short");
Output
password = "correct horse"
confirm = "correct"
confirm = "correct horse"
submit enabled
password = "short"
submit disabled

This is the usual form in user interface toolkits. The widget is a subject in the sense of Observer pattern, and the form is its observer. What makes the form a mediator is not the way it receives the events. It is that the form holds the rules that join several widgets, and that it changes the other widgets in reply.

Example

Each example file builds the checkout form and runs the six steps above.

Language Colleague to mediator Mediator to colleague
Python self.mediator.changed(self) method calls on attributes
JavaScript this.mediator.changed(this) method calls on fields
TypeScript a Mediator interface method calls on readonly fields
Java a Mediator interface in a final field method calls on final fields
C# an IMediator in a primary constructor method calls on properties
Go a Mediator interface in an unexported field method calls on struct fields
Rust each widget method returns an Event; no back reference the mediator owns the widgets
C++ a Mediator& member method calls on member objects
PythonGitHub
from abc import ABC, abstractmethod


class Mediator(ABC):
    @abstractmethod
    def changed(self, widget: "Widget") -> None: ...


class Widget:
    """A colleague. It knows its mediator and no other widget."""

    def __init__(self, name: str, mediator: Mediator):
        self.name = name
        self.mediator = mediator


class Select(Widget):
    def __init__(self, name: str, mediator: Mediator):
        super().__init__(name, mediator)
        self.value = ""

    def choose(self, value: str) -> None:  # the user picks a value
        self.value = value
        print(f'{self.name} = "{value}"')
        self.mediator.changed(self)


class TextField(Widget):
    def __init__(self, name: str, mediator: Mediator):
        super().__init__(name, mediator)
        self.text = ""

    def type(self, text: str) -> None:  # the user edits the text
        self.set_text(text)
        self.mediator.changed(self)

    def set_text(self, text: str) -> None:  # the program sets the text: no notification
        self.text = text
        print(f'{self.name} = "{text}"')


class Button(Widget):
    def __init__(self, name: str, mediator: Mediator):
        super().__init__(name, mediator)
        self.enabled = False

    def set_enabled(self, enabled: bool) -> None:
        if enabled != self.enabled:
            self.enabled = enabled
            print(f"{self.name} {'enabled' if enabled else 'disabled'}")

    def click(self) -> None:
        if self.enabled:
            self.mediator.changed(self)


class CheckoutForm(Mediator):
    """The mediator. All rules that join the widgets are here."""

    POSTCODE_LENGTH = {"US": 5, "NL": 6}

    def __init__(self):
        self.country = Select("country", self)
        self.postcode = TextField("postcode", self)
        self.submit = Button("submit", self)

    def changed(self, widget: Widget) -> None:
        if widget is self.country:
            self.postcode.set_text("")
            self.submit.set_enabled(False)
        elif widget is self.postcode:
            needed = self.POSTCODE_LENGTH.get(self.country.value)
            self.submit.set_enabled(len(self.postcode.text) == needed)
        elif widget is self.submit:
            print(f"order sent to {self.country.value} {self.postcode.text}")


form = CheckoutForm()
form.country.choose("US")
form.postcode.type("1234")
form.postcode.type("12345")
form.country.choose("NL")
form.postcode.type("1234AB")
form.submit.click()
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. Each widget holds a reference to its mediator and calls changed(self). The form tests which widget changed and applies the rules.
  • The widgets are reusable. TextField and Button have no code about countries or postcodes, so another form can use them with other rules.
  • type notifies the mediator and set_text does not. The mediator calls set_text, so its own changes do not come back to it as events. The node page shows the loop that this split prevents.
  • In Python a mediator can also be a set of callbacks: field.on_change = form.postcode_changed. A bound method is a first-class value, so the widget needs no Mediator base class.
#include <iostream>
#include <map>
#include <string>
#include <utility>

class Widget;

class Mediator {
public:
    virtual void changed(const Widget& widget) = 0;

protected:
    ~Mediator() = default;
};

// A colleague. It knows its mediator and no other widget.
class Widget {
public:
    Widget(std::string name, Mediator& mediator) : name_(std::move(name)), mediator_(mediator) {}
    const std::string& name() const { return name_; }

protected:
    void notify() const { mediator_.changed(*this); }

private:
    std::string name_;
    Mediator& mediator_;
};

class Select : public Widget {
public:
    using Widget::Widget;
    const std::string& value() const { return value_; }
    void choose(const std::string& value) {
        value_ = value;
        std::cout << name() << " = \"" << value << "\"\n";
        notify();
    }

private:
    std::string value_;
};

class TextField : public Widget {
public:
    using Widget::Widget;
    const std::string& text() const { return text_; }
    void type(const std::string& text) {  // the user edits the text
        set_text(text);
        notify();
    }
    void set_text(const std::string& text) {  // the program sets the text: no notification
        text_ = text;
        std::cout << name() << " = \"" << text << "\"\n";
    }

private:
    std::string text_;
};

class Button : public Widget {
public:
    using Widget::Widget;
    void set_enabled(bool enabled) {
        if (enabled == enabled_) return;
        enabled_ = enabled;
        std::cout << name() << (enabled ? " enabled" : " disabled") << '\n';
    }
    void click() const {
        if (enabled_) notify();
    }

private:
    bool enabled_ = false;
};

// The mediator. All rules that join the widgets are here.
class CheckoutForm final : public Mediator {
public:
    CheckoutForm() = default;
    CheckoutForm(const CheckoutForm&) = delete;  // a copy's widgets would refer to this form
    CheckoutForm& operator=(const CheckoutForm&) = delete;

    Select country{"country", *this};
    TextField postcode{"postcode", *this};
    Button submit{"submit", *this};

    void changed(const Widget& widget) override {
        if (&widget == &country) {
            postcode.set_text("");
            submit.set_enabled(false);
        } else if (&widget == &postcode) {
            auto needed = lengths_.find(country.value());
            submit.set_enabled(needed != lengths_.end() && postcode.text().size() == needed->second);
        } else if (&widget == &submit) {
            std::cout << "order sent to " << country.value() << ' ' << postcode.text() << '\n';
        }
    }

private:
    const std::map<std::string, std::size_t> lengths_{{"US", 5}, {"NL", 6}};
};

int main() {
    CheckoutForm form;
    form.country.choose("US");
    form.postcode.type("1234");
    form.postcode.type("12345");
    form.country.choose("NL");
    form.postcode.type("1234AB");
    form.submit.click();
}
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. An abstract Mediator, widgets that hold a Mediator&, and a form whose members are the widgets.
  • The form passes *this to its members as they are built. The widgets only store the reference during construction and do not call it, so the form need not be complete yet.
  • The form deletes its copy operations. A copy's widgets would still refer to the old form. With the copy constructor deleted, the compiler does not declare a move constructor either, so a move is a compile error too.
  • &widget == &country compares addresses, so it is an identity test. The program prints the rules' results and not the addresses.
JavaGitHub
import java.util.Map;

public class Main {
    interface Mediator {
        void changed(Widget widget);
    }

    /** A colleague. It knows its mediator and no other widget. */
    abstract static class Widget {
        final String name;
        final Mediator mediator;

        Widget(String name, Mediator mediator) {
            this.name = name;
            this.mediator = mediator;
        }
    }

    static final class Select extends Widget {
        String value = "";

        Select(String name, Mediator mediator) { super(name, mediator); }

        void choose(String value) {
            this.value = value;
            System.out.println(name + " = \"" + value + "\"");
            mediator.changed(this);
        }
    }

    static final class TextField extends Widget {
        String text = "";

        TextField(String name, Mediator mediator) { super(name, mediator); }

        void type(String text) { // the user edits the text
            setText(text);
            mediator.changed(this);
        }

        void setText(String text) { // the program sets the text: no notification
            this.text = text;
            System.out.println(name + " = \"" + text + "\"");
        }
    }

    static final class Button extends Widget {
        boolean enabled = false;

        Button(String name, Mediator mediator) { super(name, mediator); }

        void setEnabled(boolean enabled) {
            if (enabled != this.enabled) {
                this.enabled = enabled;
                System.out.println(name + (enabled ? " enabled" : " disabled"));
            }
        }

        void click() {
            if (enabled) mediator.changed(this);
        }
    }

    /** The mediator. All rules that join the widgets are here. */
    static final class CheckoutForm implements Mediator {
        private static final Map<String, Integer> POSTCODE_LENGTH = Map.of("US", 5, "NL", 6);
        final Select country = new Select("country", this);
        final TextField postcode = new TextField("postcode", this);
        final Button submit = new Button("submit", this);

        @Override
        public void changed(Widget widget) {
            if (widget == country) {
                postcode.setText("");
                submit.setEnabled(false);
            } else if (widget == postcode) {
                Integer needed = POSTCODE_LENGTH.get(country.value);
                submit.setEnabled(needed != null && postcode.text.length() == needed);
            } else if (widget == submit) {
                System.out.println("order sent to " + country.value + " " + postcode.text);
            }
        }
    }

    public static void main(String[] args) {
        CheckoutForm form = new CheckoutForm();
        form.country.choose("US");
        form.postcode.type("1234");
        form.postcode.type("12345");
        form.country.choose("NL");
        form.postcode.type("1234AB");
        form.submit.click();
    }
}
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. A Mediator interface with one method, widgets that hold it in a final field, and a form that implements it.
  • The form passes this to the widgets in its field initializers. This lets this escape before the constructor ends. It is safe here because no widget calls the mediator during construction.
  • Swing's ButtonGroup is a small mediator from the JDK. Turning on one button in a group turns off the others, and no button knows the others.
  • needed != null guards the lookup. A country with no entry leaves the button disabled, and it does not throw a NullPointerException on the unboxing of needed.
using System;
using System.Collections.Generic;

var form = new CheckoutForm();
form.Country.Choose("US");
form.Postcode.Type("1234");
form.Postcode.Type("12345");
form.Country.Choose("NL");
form.Postcode.Type("1234AB");
form.Submit.Click();

interface IMediator
{
    void Changed(Widget widget);
}

// A colleague. It knows its mediator and no other widget.
abstract class Widget(string name, IMediator mediator)
{
    public string Name { get; } = name;
    protected IMediator Mediator { get; } = mediator;
}

sealed class Select(string name, IMediator mediator) : Widget(name, mediator)
{
    public string Value { get; private set; } = "";

    public void Choose(string value)
    {
        Value = value;
        Console.WriteLine($"{Name} = \"{value}\"");
        Mediator.Changed(this);
    }
}

sealed class TextField(string name, IMediator mediator) : Widget(name, mediator)
{
    public string Text { get; private set; } = "";

    public void Type(string text) // the user edits the text
    {
        SetText(text);
        Mediator.Changed(this);
    }

    public void SetText(string text) // the program sets the text: no notification
    {
        Text = text;
        Console.WriteLine($"{Name} = \"{text}\"");
    }
}

sealed class Button(string name, IMediator mediator) : Widget(name, mediator)
{
    public bool Enabled { get; private set; }

    public void SetEnabled(bool enabled)
    {
        if (enabled == Enabled) return;
        Enabled = enabled;
        Console.WriteLine($"{Name} {(enabled ? "enabled" : "disabled")}");
    }

    public void Click()
    {
        if (Enabled) Mediator.Changed(this);
    }
}

// The mediator. All rules that join the widgets are here.
sealed class CheckoutForm : IMediator
{
    private static readonly Dictionary<string, int> PostcodeLength = new() { ["US"] = 5, ["NL"] = 6 };

    public Select Country { get; }
    public TextField Postcode { get; }
    public Button Submit { get; }

    public CheckoutForm()
    {
        Country = new Select("country", this);
        Postcode = new TextField("postcode", this);
        Submit = new Button("submit", this);
    }

    public void Changed(Widget widget)
    {
        if (widget == Country)
        {
            Postcode.SetText("");
            Submit.SetEnabled(false);
        }
        else if (widget == Postcode)
        {
            Submit.SetEnabled(PostcodeLength.TryGetValue(Country.Value, out int needed) && Postcode.Text.Length == needed);
        }
        else if (widget == Submit)
        {
            Console.WriteLine($"order sent to {Country.Value} {Postcode.Text}");
        }
    }
}
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. An IMediator interface, widgets with primary constructors that take it, and a form that implements it.
  • The form makes its widgets in its constructor, because a field initializer in C# cannot refer to this.
  • The usual .NET form of a mediator is events. Each widget exposes an event EventHandler Changed, and the form subscribes with +=. The widgets then hold no reference of their own to the form, but the event's delegate list does.
JavaScriptGitHub
// The colleagues. Each widget knows its mediator and no other widget.
class Select {
  value = "";
  constructor(name, mediator) {
    this.name = name;
    this.mediator = mediator;
  }
  choose(value) {
    this.value = value;
    console.log(`${this.name} = "${value}"`);
    this.mediator.changed(this);
  }
}

class TextField {
  text = "";
  constructor(name, mediator) {
    this.name = name;
    this.mediator = mediator;
  }
  type(text) {
    this.setText(text); // the user edits the text
    this.mediator.changed(this);
  }
  setText(text) {
    this.text = text; // the program sets the text: no notification
    console.log(`${this.name} = "${text}"`);
  }
}

class Button {
  enabled = false;
  constructor(name, mediator) {
    this.name = name;
    this.mediator = mediator;
  }
  setEnabled(enabled) {
    if (enabled !== this.enabled) {
      this.enabled = enabled;
      console.log(`${this.name} ${enabled ? "enabled" : "disabled"}`);
    }
  }
  click() {
    if (this.enabled) this.mediator.changed(this);
  }
}

// The mediator. All rules that join the widgets are here.
class CheckoutForm {
  static postcodeLength = { US: 5, NL: 6 };
  country = new Select("country", this);
  postcode = new TextField("postcode", this);
  submit = new Button("submit", this);

  changed(widget) {
    if (widget === this.country) {
      this.postcode.setText("");
      this.submit.setEnabled(false);
    } else if (widget === this.postcode) {
      const needed = CheckoutForm.postcodeLength[this.country.value];
      this.submit.setEnabled(this.postcode.text.length === needed);
    } else if (widget === this.submit) {
      console.log(`order sent to ${this.country.value} ${this.postcode.text}`);
    }
  }
}

const form = new CheckoutForm();
form.country.choose("US");
form.postcode.type("1234");
form.postcode.type("12345");
form.country.choose("NL");
form.postcode.type("1234AB");
form.submit.click();
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. The widgets call mediator.changed(this), and the form holds all the rules.
  • Class fields run in order, and this in a field initializer is the instance under construction, so the form can pass itself to each widget as it makes it.
  • In a browser the DOM gives the other form. Each element is an EventTarget, and the form adds listeners to the widgets. The widgets then know nothing of the mediator, and the mediator is an observer of each widget. The node page has that version.
TypeScriptGitHub
type Country = "US" | "NL";

interface Mediator {
  changed(widget: Widget): void;
}

// A colleague. It knows its mediator and no other widget.
abstract class Widget {
  readonly name: string;
  protected readonly mediator: Mediator;
  constructor(name: string, mediator: Mediator) {
    this.name = name;
    this.mediator = mediator;
  }
}

class Select<T extends string> extends Widget {
  value: T | undefined;
  choose(value: T): void {
    this.value = value;
    console.log(`${this.name} = "${value}"`);
    this.mediator.changed(this);
  }
}

class TextField extends Widget {
  text = "";
  type(text: string): void {
    this.setText(text); // the user edits the text
    this.mediator.changed(this);
  }
  setText(text: string): void {
    this.text = text; // the program sets the text: no notification
    console.log(`${this.name} = "${text}"`);
  }
}

class Button extends Widget {
  enabled = false;
  setEnabled(enabled: boolean): void {
    if (enabled !== this.enabled) {
      this.enabled = enabled;
      console.log(`${this.name} ${enabled ? "enabled" : "disabled"}`);
    }
  }
  click(): void {
    if (this.enabled) this.mediator.changed(this);
  }
}

// The mediator. All rules that join the widgets are here.
class CheckoutForm implements Mediator {
  static readonly postcodeLength: Readonly<Record<Country, number>> = { US: 5, NL: 6 };
  readonly country = new Select<Country>("country", this);
  readonly postcode = new TextField("postcode", this);
  readonly submit = new Button("submit", this);

  changed(widget: Widget): void {
    if (widget === this.country) {
      this.postcode.setText("");
      this.submit.setEnabled(false);
    } else if (widget === this.postcode && this.country.value !== undefined) {
      const needed = CheckoutForm.postcodeLength[this.country.value];
      this.submit.setEnabled(this.postcode.text.length === needed);
    } else if (widget === this.submit) {
      console.log(`order sent to ${this.country.value} ${this.postcode.text}`);
    }
  }
}

const form = new CheckoutForm();
form.country.choose("US");
form.postcode.type("1234");
form.postcode.type("12345");
form.country.choose("NL");
form.postcode.type("1234AB");
form.submit.click();
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. A Mediator interface, an abstract Widget that holds it, and a form that implements it.
  • Select<Country> lets the compiler reject form.country.choose("FR"), and Record<Country, number> makes the compiler check that each country has a postcode length.
  • changed takes a Widget and tests it with ===. A discriminated union of events, such as { kind: "country"; value: Country }, would let the compiler check that the form handles each kind. The Rust example takes that approach.
package main

import "fmt"

// Mediator is told when a widget changes.
type Mediator interface {
	Changed(widget any)
}

// Select, TextField and Button are colleagues. Each knows its mediator and no other widget.
type Select struct {
	Name     string
	Value    string
	mediator Mediator
}

func (s *Select) Choose(value string) {
	s.Value = value
	fmt.Printf("%s = %q\n", s.Name, value)
	s.mediator.Changed(s)
}

type TextField struct {
	Name     string
	Text     string
	mediator Mediator
}

// Type is a user edit: it notifies the mediator.
func (t *TextField) Type(text string) {
	t.SetText(text)
	t.mediator.Changed(t)
}

// SetText is a program edit: no notification.
func (t *TextField) SetText(text string) {
	t.Text = text
	fmt.Printf("%s = %q\n", t.Name, text)
}

type Button struct {
	Name     string
	Enabled  bool
	mediator Mediator
}

func (b *Button) SetEnabled(enabled bool) {
	if enabled == b.Enabled {
		return
	}
	b.Enabled = enabled
	state := "disabled"
	if enabled {
		state = "enabled"
	}
	fmt.Println(b.Name, state)
}

func (b *Button) Click() {
	if b.Enabled {
		b.mediator.Changed(b)
	}
}

// CheckoutForm is the mediator. All rules that join the widgets are here.
type CheckoutForm struct {
	Country  *Select
	Postcode *TextField
	Submit   *Button
}

var postcodeLength = map[string]int{"US": 5, "NL": 6}

func NewCheckoutForm() *CheckoutForm {
	f := &CheckoutForm{}
	f.Country = &Select{Name: "country", mediator: f}
	f.Postcode = &TextField{Name: "postcode", mediator: f}
	f.Submit = &Button{Name: "submit", mediator: f}
	return f
}

func (f *CheckoutForm) Changed(widget any) {
	switch widget {
	case f.Country:
		f.Postcode.SetText("")
		f.Submit.SetEnabled(false)
	case f.Postcode:
		needed, ok := postcodeLength[f.Country.Value]
		f.Submit.SetEnabled(ok && len(f.Postcode.Text) == needed)
	case f.Submit:
		fmt.Println("order sent to", f.Country.Value, f.Postcode.Text)
	}
}

func main() {
	form := NewCheckoutForm()
	form.Country.Choose("US")
	form.Postcode.Type("1234")
	form.Postcode.Type("12345")
	form.Country.Choose("NL")
	form.Postcode.Type("1234AB")
	form.Submit.Click()
}
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. A Mediator interface, widgets that hold it in an unexported field, and a form whose Changed method switches on the widget.
  • switch widget with case f.Country compares an any with a *Select. The comparison is true when the dynamic type and the pointer are both equal, so it is an identity test.
  • The pointers form a cycle: the form points to the widgets and each widget points back to the form. A garbage collector frees such a cycle when nothing else refers to it.
  • A channel of events is the other Go form. The widgets send to the channel, and one goroutine runs the rules. This also makes the mediator the only goroutine that changes the widgets.
RustGitHub
#[derive(Clone, Copy, PartialEq)]
enum Country {
    Us,
    Nl,
}

impl Country {
    fn code(self) -> &'static str {
        match self {
            Country::Us => "US",
            Country::Nl => "NL",
        }
    }
    fn postcode_length(self) -> usize {
        match self {
            Country::Us => 5,
            Country::Nl => 6,
        }
    }
}

/// What a widget tells the mediator. The widgets hold no reference to it.
enum Event {
    CountryChosen,
    PostcodeTyped,
    SubmitClicked,
}

struct Select {
    name: &'static str,
    value: Option<Country>,
}

impl Select {
    fn choose(&mut self, value: Country) -> Option<Event> {
        self.value = Some(value);
        println!("{} = \"{}\"", self.name, value.code());
        Some(Event::CountryChosen)
    }
}

struct TextField {
    name: &'static str,
    text: String,
}

impl TextField {
    /// A user edit: it returns an event for the mediator.
    fn type_text(&mut self, text: &str) -> Option<Event> {
        self.set_text(text);
        Some(Event::PostcodeTyped)
    }
    /// A program edit: no event.
    fn set_text(&mut self, text: &str) {
        self.text = text.to_string();
        println!("{} = \"{}\"", self.name, text);
    }
}

struct Button {
    name: &'static str,
    enabled: bool,
}

impl Button {
    fn set_enabled(&mut self, enabled: bool) {
        if enabled != self.enabled {
            self.enabled = enabled;
            println!("{} {}", self.name, if enabled { "enabled" } else { "disabled" });
        }
    }
    fn click(&self) -> Option<Event> {
        self.enabled.then_some(Event::SubmitClicked)
    }
}

/// The mediator. It owns the widgets, and all rules that join them are here.
struct CheckoutForm {
    country: Select,
    postcode: TextField,
    submit: Button,
}

impl CheckoutForm {
    fn new() -> Self {
        CheckoutForm {
            country: Select { name: "country", value: None },
            postcode: TextField { name: "postcode", text: String::new() },
            submit: Button { name: "submit", enabled: false },
        }
    }

    fn changed(&mut self, event: Event) {
        match event {
            Event::CountryChosen => {
                self.postcode.set_text("");
                self.submit.set_enabled(false);
            }
            Event::PostcodeTyped => {
                let valid = self
                    .country
                    .value
                    .is_some_and(|c| self.postcode.text.len() == c.postcode_length());
                self.submit.set_enabled(valid);
            }
            Event::SubmitClicked => {
                let code = self.country.value.map_or("", Country::code);
                println!("order sent to {} {}", code, self.postcode.text);
            }
        }
    }
}

/// The steps of the user, in order.
enum Action {
    Choose(Country),
    Type(&'static str),
    Click,
}

fn main() {
    let mut form = CheckoutForm::new();
    let actions = [
        Action::Choose(Country::Us),
        Action::Type("1234"),
        Action::Type("12345"),
        Action::Choose(Country::Nl),
        Action::Type("1234AB"),
        Action::Click,
    ];
    for action in actions {
        let event = match action {
            Action::Choose(country) => form.country.choose(country),
            Action::Type(text) => form.postcode.type_text(text),
            Action::Click => form.submit.click(),
        };
        if let Some(event) = event {
            form.changed(event);
        }
    }
}
Output
country = "US"
postcode = ""
postcode = "1234"
postcode = "12345"
submit enabled
country = "NL"
postcode = ""
submit disabled
postcode = "1234AB"
submit enabled
order sent to NL 1234AB
  • Verdict: idiom. The mediator owns the widgets, each widget method returns an Event, and the caller passes the event to changed. No widget holds a reference to the form.
  • A widget that holds &mut CheckoutForm while the form owns the widget does not compile. Two &mut paths to one value break the borrow rules. Rc<RefCell<...>> and Weak back references can model the classic form, but the borrow is then checked at run time.
  • match on the Event enum is exhaustive. An event kind added to the enum and not handled in changed is a compile error.

Consequences

Design Patterns lists five consequences.1

  • It limits subclassing. The behaviour that would be spread across the colleagues is in the mediator. A change of behaviour needs a subclass of the mediator, or a different mediator, and the colleague classes stay as they are.
  • It decouples colleagues. Colleague classes can change and be reused on their own.
  • It simplifies object protocols. One-to-many links between a mediator and its colleagues replace many-to-many links between colleagues. One-to-many links are less work to understand, maintain and extend.
  • It abstracts how objects cooperate. The way objects interact becomes a concept of its own, in an object of its own.
  • It centralizes control. The complexity of the interaction moves into the mediator. Design Patterns warns that this can make the mediator more complex than any of the colleagues, and a monolith that is hard to maintain.

The last point is the main liability. A mediator for a large dialog collects every rule of the dialog. It knows the concrete type of each widget, and each rule added to it makes it larger. A mediator that grows this way is a god object, and splitting it means finding groups of widgets that interact mostly with each other and giving each group its own mediator.

The links between the mediator and its colleagues form a cycle. In a language with garbage collection, that is no problem. In Rust and in C++ it needs a decision about ownership. The Rust example gives the mediator ownership of the widgets and lets the widgets return events in place of a back reference.

When not to use it

Do not use it for two objects. A mediator between two colleagues is a third class with no gain. A direct reference, or one observer, is clearer.

Do not use it when the objects do not interact with each other. Objects that only report to one consumer need an observer or a callback. The mediator is for rules that read one colleague and change another.

Do not use a global event bus as a mediator by default. A bus removes the references between objects, but it also removes the place where a reader can see the rules. Each subscriber holds a part of the logic, and the coupling is still there, through the names of the events. Fowler's Event Aggregator is a single source of events for many objects, and it fits the case where many objects want to hear about many sources.2 It does not hold the rules, so it is not a mediator in the sense of Design Patterns.

Observer. Observer sends one subject's changes to any number of observers, and the subject does not know what they do. A mediator holds the rules between several objects and acts on them. Design Patterns says that colleagues can talk to the mediator through Observer.1 Peter Norvig groups Mediator and Observer together, as patterns that method combination makes invisible or simpler in a dynamic language such as Lisp or Dylan.3 See Observer pattern.

Facade. Design Patterns compares the two.1 A facade gives a more convenient interface to a subsystem, and its protocol goes one way: the facade calls the subsystem, and the subsystem does not know the facade. A mediator's colleagues know the mediator and call it, so its protocol goes both ways. See Facade pattern.

Event aggregator and event bus. An event aggregator collects the events of many objects and gives them to subscribers in one place.2 It removes references between objects as a mediator does, but it moves no rules. A mediator can be built on top of one: the mediator subscribes to the bus, and the bus delivers the events.

Command. Colleagues can send commands to the mediator in place of method calls, and the mediator can run, log or queue them. See Command pattern.

Chain of Responsibility. A chain passes a request along a list of handlers, and each one decides whether to handle it. A mediator receives the request and decides itself who acts. See Chain of Responsibility pattern.

Controllers and view models. The controller of a form in a model-view-controller design and the view model of a form often play the role of a mediator. They hold the rules that join the widgets of one view.

Known uses

  • Swing ButtonGroup: a set of buttons with the same ButtonGroup forms a multiple-exclusion scope. Turning one button on turns off all the others in the group.6 No button knows the others.
  • HTML radio buttons: inputs of type radio in the same form with the same name are one radio button group. When one becomes checked, the browser sets all the others in the group to unchecked.7
  • DOM event handling: a form script that adds event listeners to its fields and changes other fields in reply is a mediator built on EventTarget.4

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Mediator (Intent, Motivation, Applicability, Participants, Consequences, Implementation, Related Patterns)
  2. Martin Fowler, Event Aggregator, How it Works; When to Use It
  3. Peter Norvig, Design Patterns in Dynamic Programming, Object World, 1996, slide 10, Design Patterns in Dylan or Lisp
  4. DOM Living Standard, WHATWG, 2.7 Interface EventTarget
  5. The Python Standard Library, Built-in Exceptions, Python 3.14, RecursionError
  6. Java SE 25 API, javax.swing.ButtonGroup, class description
  7. HTML Living Standard, WHATWG, 4.10.5.1.16 Radio Button state (type=radio)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/DPXJHB/text.yaml