Mediator Pattern

Route all communication between a group of objects through one coordinator, so the objects know the coordinator and not each other.

Overview

The problem: everyone talks to everyone

A checkout form has a country dropdown, a state dropdown, a postal code field, a shipping-method list and a Pay button. Change the country, and the state list must reload, the postal code must re-validate, shipping options must change, and the button must disable until the form is valid again. If each widget calls the others directly, every widget ends up holding references to most of the rest.

The number of possible pairs grows fast. With n objects there are n(n-1)/2 pairs. Five objects have 5 × 4 / 2 = 10 possible direct links, ten objects have 10 × 9 / 2 = 45, and twenty have 20 × 19 / 2 = 190. Route the same objects through one mediator and each needs a single link, so the counts drop to 5, 10 and 20.

Every direct link is a reason one class cannot be changed, tested or reused without another. The Mediator pattern replaces the web with a star.

Interview questions

  • Show the smell Mediator fixes, and the fix.
  • How is Mediator different from Observer?
  • How do you keep the mediator from becoming a god object?
  • How do colleagues get their mediator, and how do you test them?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio