Polski

Article · Mediator · CQRS

Mediator: components talk through a coordinator

The Mediator pattern through the order form of a pierogi place: the delivery choice, address, time slot and button do not know each other, and the rules of their cooperation live in one place. Plus an honest look at MediatR and code in five languages.

By · · 12 min read

The order form on the website of Halina's pierogi place has four elements: a "pickup/delivery" toggle, an address field, a time slot picker and an "Order" button. It sounds simple until it turns out that everything affects everything: delivery shows the address and changes the time slots, and the button depends on all three. Mediator takes this knowledge away from the components and keeps it in one object.

4
form components – toggle, address, time slot, button
12 → 4
possible dependencies – an all-to-all mesh vs a star
1
place for the rules – the mediator's notify method

The problem: a mesh of dependencies

The first version of the form wired reactions directly to the components:

order-form-before.ts
deliveryToggle.onChange = (mode) => {
  addressField.visible = mode === 'delivery';
  slotPicker.load(mode === 'delivery' ? deliverySlots : pickupSlots);
  submitButton.enabled = !!slotPicker.selected && (mode === 'pickup' || addressField.value !== '');
};
addressField.onChange = (value) => {
  submitButton.enabled = !!slotPicker.selected && (deliveryToggle.mode === 'pickup' || value !== '');
};
slotPicker.onChange = (slot) => {
  submitButton.enabled = !!slot && (deliveryToggle.mode === 'pickup' || addressField.value !== ''); // third copy
};

The button's enabling condition exists in three copies and they already differ (!!slotPicker.selected vs !!slot). The toggle has to know the address, the slot list and the button; the address field has to know the toggle and the button. The components cannot be reused in another form, because each drags the others along. With four elements there are twelve possible connections – with eight there would be fifty-six.

Diagram: Without a mediator: everyone knows everyone
Diagram: With a mediator: a star

The solution: a single coordinator

Every component gets a reference to the mediator and calls mediator.notify(this) on every change. It does not know who will react or how. The mediator – here the OrderForm itself – knows all the components and decides in one method what follows from what: choosing delivery shows the address and loads delivery slots, and every change recalculates the button's state.

Diagram: The customer switches from delivery to pickup
RoleIn the exampleResponsibility
MediatorFormMediatorthe interface through which components report changes
Concrete mediatorOrderFormknows the components, holds the rules of their cooperation
ColleagueComponentonly knows the mediator
Concrete colleaguesDeliveryMode, AddressField, SlotPicker, SubmitButtontheir own state and behaviour, unaware of the others

Implementation in five languages

The components are deliberately "dumb": they keep their state and report a change. All the dependency logic sits in the mediator's notify method. In Go the button is simply a SubmitEnabled field, and the mediator recognises the sender by its pointer.

Mediator – order form

OrderForm.cs
var form = new OrderForm();
form.Mode.Choose("delivery");           // address shown, delivery slots loaded
form.Address.Type("Długa 5");
form.Slots.Pick("18:30");
Console.WriteLine(form.Submit.Enabled); // True
form.Mode.Choose("pickup");             // address hidden, slot reset
Console.WriteLine(form.Submit.Enabled); // False

public interface IFormMediator
{
    void Notify(Component sender);
}

// Components only know the mediator, never each other.
public abstract class Component(IFormMediator mediator)
{
    protected void Changed() => mediator.Notify(this);
}

public sealed class DeliveryMode(IFormMediator m) : Component(m)
{
    public string Value { get; private set; } = "pickup";
    public void Choose(string value) { Value = value; Changed(); }
}

public sealed class AddressField(IFormMediator m) : Component(m)
{
    public bool Visible { get; set; }
    public string Text { get; private set; } = "";
    public void Type(string text) { Text = text; Changed(); }
}

public sealed class SlotPicker(IFormMediator m) : Component(m)
{
    public string[] Options { get; set; } = [];
    public string? Selected { get; set; }
    public void Pick(string slot) { Selected = Options.Contains(slot) ? slot : null; Changed(); }
}

public sealed class SubmitButton(IFormMediator m) : Component(m)
{
    public bool Enabled { get; set; }
}

// The mediator is the only place that knows how components affect each other.
public sealed class OrderForm : IFormMediator
{
    public DeliveryMode Mode { get; }
    public AddressField Address { get; }
    public SlotPicker Slots { get; }
    public SubmitButton Submit { get; }

    public OrderForm()
    {
        (Mode, Address, Slots, Submit) = (new(this), new(this), new(this), new(this));
        Notify(Mode);
    }

    public void Notify(Component sender)
    {
        if (sender == Mode)
        {
            Address.Visible = Mode.Value == "delivery";
            Slots.Options = Address.Visible ? ["18:30", "19:00"] : ["17:45", "18:00", "18:15"];
            Slots.Selected = null;
        }
        Submit.Enabled = Slots.Selected is not null && (!Address.Visible || Address.Text.Length > 0);
    }
}
order-form.ts
interface FormMediator {
  notify(sender: Component): void;
}

// Components only know the mediator, never each other.
abstract class Component {
  constructor(protected readonly mediator: FormMediator) {}
  protected changed(): void { this.mediator.notify(this); }
}

class DeliveryMode extends Component {
  value: 'pickup' | 'delivery' = 'pickup';
  choose(value: 'pickup' | 'delivery'): void { this.value = value; this.changed(); }
}

class AddressField extends Component {
  visible = false;
  text = '';
  type(text: string): void { this.text = text; this.changed(); }
}

class SlotPicker extends Component {
  options: string[] = [];
  selected: string | null = null;
  pick(slot: string): void { this.selected = this.options.includes(slot) ? slot : null; this.changed(); }
}

class SubmitButton extends Component {
  enabled = false;
}

// The mediator is the only place that knows how components affect each other.
class OrderForm implements FormMediator {
  readonly mode = new DeliveryMode(this);
  readonly address = new AddressField(this);
  readonly slots = new SlotPicker(this);
  readonly submit = new SubmitButton(this);

  constructor() { this.notify(this.mode); }

  notify(sender: Component): void {
    if (sender === this.mode) {
      this.address.visible = this.mode.value === 'delivery';
      this.slots.options = this.address.visible ? ['18:30', '19:00'] : ['17:45', '18:00', '18:15'];
      this.slots.selected = null;
    }
    this.submit.enabled = this.slots.selected !== null && (!this.address.visible || this.address.text !== '');
  }
}

const form = new OrderForm();
form.mode.choose('delivery');
form.address.type('Długa 5');
form.slots.pick('18:30');
console.log(form.submit.enabled); // true
form.mode.choose('pickup');
console.log(form.submit.enabled); // false – pick a pickup slot first
OrderForm.java
import java.util.List;

interface FormMediator {
    void notify(Component sender);
}

// Components only know the mediator, never each other.
abstract class Component {
    private final FormMediator mediator;
    Component(FormMediator mediator) { this.mediator = mediator; }
    protected void changed() { mediator.notify(this); }
}

class DeliveryMode extends Component {
    String value = "pickup";
    DeliveryMode(FormMediator m) { super(m); }
    void choose(String value) { this.value = value; changed(); }
}

class AddressField extends Component {
    boolean visible;
    String text = "";
    AddressField(FormMediator m) { super(m); }
    void type(String text) { this.text = text; changed(); }
}

class SlotPicker extends Component {
    List<String> options = List.of();
    String selected;
    SlotPicker(FormMediator m) { super(m); }
    void pick(String slot) { selected = options.contains(slot) ? slot : null; changed(); }
}

class SubmitButton extends Component {
    boolean enabled;
    SubmitButton(FormMediator m) { super(m); }
}

// The mediator is the only place that knows how components affect each other.
public class OrderForm implements FormMediator {
    final DeliveryMode mode = new DeliveryMode(this);
    final AddressField address = new AddressField(this);
    final SlotPicker slots = new SlotPicker(this);
    final SubmitButton submit = new SubmitButton(this);

    OrderForm() { notify(mode); }

    @Override public void notify(Component sender) {
        if (sender == mode) {
            address.visible = mode.value.equals("delivery");
            slots.options = address.visible ? List.of("18:30", "19:00") : List.of("17:45", "18:00", "18:15");
            slots.selected = null;
        }
        submit.enabled = slots.selected != null && (!address.visible || !address.text.isEmpty());
    }

    public static void main(String[] args) {
        var form = new OrderForm();
        form.mode.choose("delivery");
        form.address.type("Długa 5");
        form.slots.pick("18:30");
        System.out.println(form.submit.enabled); // true
        form.mode.choose("pickup");
        System.out.println(form.submit.enabled); // false
    }
}
order_form.go
package main

import (
	"fmt"
	"slices"
)

// Mediator is the only thing components know about.
type Mediator interface{ Changed(sender any) }

type DeliveryMode struct {
	m     Mediator
	Value string
}

func (d *DeliveryMode) Choose(v string) {
	d.Value = v
	d.m.Changed(d)
}

type AddressField struct {
	m       Mediator
	Visible bool
	Text    string
}

func (a *AddressField) Type(t string) {
	a.Text = t
	a.m.Changed(a)
}

type SlotPicker struct {
	m        Mediator
	Options  []string
	Selected string
}

func (s *SlotPicker) Pick(slot string) {
	s.Selected = ""
	if slices.Contains(s.Options, slot) {
		s.Selected = slot
	}
	s.m.Changed(s)
}

// OrderForm coordinates the components; the submit button is just a flag here.
type OrderForm struct {
	Mode          DeliveryMode
	Address       AddressField
	Slots         SlotPicker
	SubmitEnabled bool
}

func NewOrderForm() *OrderForm {
	f := &OrderForm{}
	f.Mode, f.Address, f.Slots = DeliveryMode{m: f, Value: "pickup"}, AddressField{m: f}, SlotPicker{m: f}
	f.Changed(&f.Mode)
	return f
}

func (f *OrderForm) Changed(sender any) {
	if sender == &f.Mode {
		f.Address.Visible = f.Mode.Value == "delivery"
		f.Slots.Options = []string{"17:45", "18:00", "18:15"}
		if f.Address.Visible {
			f.Slots.Options = []string{"18:30", "19:00"}
		}
		f.Slots.Selected = ""
	}
	f.SubmitEnabled = f.Slots.Selected != "" && (!f.Address.Visible || f.Address.Text != "")
}

func main() {
	f := NewOrderForm()
	f.Mode.Choose("delivery")
	f.Address.Type("Długa 5")
	f.Slots.Pick("18:30")
	fmt.Println(f.SubmitEnabled) // true
	f.Mode.Choose("pickup")
	fmt.Println(f.SubmitEnabled) // false
}
order_form.py
from __future__ import annotations


class Component:
    """Components only know the mediator, never each other."""

    def __init__(self, mediator: OrderForm) -> None:
        self._mediator = mediator

    def _changed(self) -> None:
        self._mediator.notify(self)


class DeliveryMode(Component):
    value = "pickup"

    def choose(self, value: str) -> None:
        self.value = value
        self._changed()


class AddressField(Component):
    visible = False
    text = ""

    def type(self, text: str) -> None:
        self.text = text
        self._changed()


class SlotPicker(Component):
    options: list[str] = []
    selected: str | None = None

    def pick(self, slot: str) -> None:
        self.selected = slot if slot in self.options else None
        self._changed()


class OrderForm:
    """The mediator: the only place that knows how components affect each other."""

    def __init__(self) -> None:
        self.mode = DeliveryMode(self)
        self.address = AddressField(self)
        self.slots = SlotPicker(self)
        self.submit_enabled = False
        self.notify(self.mode)

    def notify(self, sender: Component) -> None:
        if sender is self.mode:
            self.address.visible = self.mode.value == "delivery"
            self.slots.options = ["18:30", "19:00"] if self.address.visible else ["17:45", "18:00", "18:15"]
            self.slots.selected = None
        self.submit_enabled = self.slots.selected is not None and (
            not self.address.visible or self.address.text != ""
        )


form = OrderForm()
form.mode.choose("delivery")
form.address.type("Długa 5")
form.slots.pick("18:30")
print(form.submit_enabled)  # True
form.mode.choose("pickup")
print(form.submit_enabled)  # False

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • Mediator vs MediatR
  • When to use it and when not to
  • Related patterns
  • In practice
  • Test yourself

Create a free account · Sign in