Mediator

Make objects talk through one coordinator instead of directly to each other, so the rules about who affects whom live in one place.

Description

When many objects react to each other, every one ends up knowing every other: the country select updates shipping, shipping updates the price, the price updates the button… A mediator cuts those links. Each colleague only tells the mediator "something happened", and the mediator decides what else must change.

Colleagues become simple and reusable, since a country select no longer knows about shipping, and all the coordination rules sit together where they're easy to read and change. Form controllers, chat rooms, air-traffic control and workflow orchestrators are mediators.

Class diagram

notifiesowns all widgets«interface»Mediator+ notify(sender, event)CheckoutForm+ notify(sender, event)«abstract»Widget# mediator?: Mediator+ connect(mediator)CountrySelect+ choose(code)ShippingOptions+ setOptions(list)PriceSummary+ show(…)

Mediator pattern class diagram

  1. Interface Mediator with + notify(sender, event).
  2. Class CheckoutForm with + notify(sender, event).
  3. Abstract class Widget with + connect(mediator).
  4. Class CountrySelect with + choose(code).
  5. Class ShippingOptions with + setOptions(list).
  6. Class PriceSummary with + show(…).
  7. CheckoutForm implements Mediator.
  8. Widget notifies Mediator.
  9. CountrySelect extends Widget.
  10. ShippingOptions extends Widget.
  11. PriceSummary extends Widget.
  12. CheckoutForm owns all widgets CountrySelect.

Sequence diagram

UserCountrySelectCheckoutFormShippingOptionsPriceSummary1. choose("US")2. notify(this, "changed")3. setOptions(international)4. show(40, 149, 0)

Mediator pattern sequence diagram

  1. User → CountrySelect: choose("US").
  2. CountrySelect → CheckoutForm: notify(this, "changed").
  3. CheckoutForm → ShippingOptions: setOptions(international).
  4. CheckoutForm → PriceSummary: show(40, 149, 0).

TypeScript example

A checkout form as mediator. The country select, shipping options and price summary never reference each other; the form holds the rules that connect them.

mediator.ts
// Mediator: form widgets don't talk to each other; they tell the form,
// and the form decides what else must change.

interface Mediator {
  notify(sender: Widget, event: string): void;
}

abstract class Widget {
  protected mediator?: Mediator;
  connect(mediator: Mediator): void {
    this.mediator = mediator;
  }
}

class CountrySelect extends Widget {
  value = "SE";
  choose(code: string): void {
    this.value = code;
    this.mediator?.notify(this, "changed");
  }
}

class ShippingOptions extends Widget {
  options: string[] = [];
  selected = "";
  setOptions(options: string[]): void {
    this.options = options;
    this.selected = options[0];
  }
}

class PriceSummary extends Widget {
  text = "";
  show(subtotal: number, shipping: number, vatRate: number): void {
    const total = (subtotal + shipping) * (1 + vatRate);
    this.text = `total ${total.toFixed(2)} (incl. ${vatRate * 100}% VAT)`;
  }
}

// Concrete mediator: all the coordination rules live here
class CheckoutForm implements Mediator {
  readonly country = new CountrySelect();
  readonly shipping = new ShippingOptions();
  readonly summary = new PriceSummary();
  private readonly subtotal = 40;

  constructor() {
    for (const w of [this.country, this.shipping, this.summary]) w.connect(this);
    this.notify(this.country, "changed"); // initial state
  }

  notify(sender: Widget, event: string): void {
    if (sender === this.country && event === "changed") {
      const domestic = this.country.value === "SE";
      this.shipping.setOptions(domestic ? ["PostNord 49", "Express 99"] : ["International 149"]);
      const cost = Number(this.shipping.selected.split(" ").pop());
      this.summary.show(this.subtotal, cost, domestic ? 0.25 : 0);
    }
  }
}

export function demo(): string[] {
  const form = new CheckoutForm();
  const lines = [`SE: ${form.shipping.options.join(", ")}; ${form.summary.text}`];
  form.country.choose("US"); // the select only tells the form
  lines.push(`US: ${form.shipping.options.join(", ")}; ${form.summary.text}`);
  return lines;
}

When to use it

Use it when

  • Several components affect each other in many directions, and the web of references is getting tangled.
  • You want to reuse components in other contexts, which is impossible while they reference their neighbours.
  • The interaction rules change often and should be in one place, such as form logic or game rules.

Avoid it when

  • Communication is one-way, from one source to many listeners. That's Observer.
  • There are only two collaborators. A direct reference is fine.
  • The mediator would need to know the internals of every colleague. You've only moved the tangle.

Pitfalls

  • The god mediator that accumulates all the application logic. Split it by screen, feature or workflow.
  • Colleagues that still call each other directly "just this once", which defeats the point.
  • Event names as loose strings ("changed") that are easy to mistype. Use typed events.

Alternatives

Observer

Choose it when one subject broadcasts to many listeners, and listeners don't affect each other.

Facade

Choose it when you need a simple entry point into a subsystem; the subsystem's parts don't need to talk back.

Saga (orchestration)

Choose it when the colleagues are separate services coordinating a long-running business process.

State management store

Choose it when in a UI, components share state through a store (Redux, signals) instead of a hand-written mediator.