Behavioral · DWG NO. 020

Mediator

Route communication between components through one hub, instead of wiring every component directly to every other.

TypeBehavioral
ScopeMultiple peer components
ComplexityMedium
Common inChat rooms, form validation, air traffic-style coordination

Every component ends up holding a reference to every other component

A form where each field needs to enable/disable other fields based on its own value — if every field directly references every other field it might affect, the field count and the reference count both grow together, and reasoning about the whole form means reading every field.

Components only know the mediator

Each component notifies the mediator when something happens to it, instead of notifying other components directly. The mediator holds the logic for how components affect each other and calls their public methods in response.

MediatorField AField BField CField D

A checkout form mediator

`CountryField` and `ShippingField` never talk to each other directly — the mediator decides that selecting an unsupported country disables shipping.

form-mediator.js
class FormMediator {
  register(name, field) { (this.fields ??= {})[name] = field; field.mediator = this; }

  notify(sender, event) {
    if (sender === "country" && event === "changed") {
      const supported = this.fields.country.value !== "antarctica";
      this.fields.shipping.setEnabled(supported);
    }
  }
}

class Field {
  constructor(name) { this.name = name; this.enabled = true; }
  setValue(value) { this.value = value; this.mediator.notify(this.name, "changed"); }
  setEnabled(enabled) {
    this.enabled = enabled;
    console.log(`${this.name}: ${enabled ? "enabled" : "disabled"}`);
  }
}

const mediator = new FormMediator();
const country = new Field("country");
const shipping = new Field("shipping");
mediator.register("country", country);
mediator.register("shipping", shipping);

country.setValue("antarctica"); // shipping: disabled
country.setValue("canada");     // shipping: enabled

Trade-offs