LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 41 OF 48

Mediator Pattern in Java: One Coordinator Instead of a Tangle

The Mediator pattern in Java with a cinema ticket checkout: seat picker, snack picker, coupon field, price label and pay button stop calling each other and report to one coordinator that owns the rules. Covers the participants, code, when to use it, the god mediator risk, how it differs from Observer and Facade, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 203 lines, with a small main() demo. Save it as TicketCheckoutDemo.java, then run javac TicketCheckoutDemo.java && java TicketCheckoutDemo.

/**
 * Mediator: widgets stop calling each other and report to one coordinator
 * that owns the rules of the cinema checkout screen.
 */
public class TicketCheckoutDemo {

    public static void main(String[] args) {
        // BEFORE: the seat picker knows the price label, pay button and coupon rule.
        OldPriceLabel oldPrice = new OldPriceLabel();
        OldSeatPicker oldSeats = new OldSeatPicker(oldPrice);
        oldSeats.select(3);
        System.out.println("Before: seat picker set the price itself -> " + oldPrice.text);
        System.out.println();

        // AFTER: every widget knows only the mediator interface.
        TicketCheckout checkout = new TicketCheckout();
        SeatPicker seats = new SeatPicker(checkout);
        SnackPicker snacks = new SnackPicker(checkout);
        CouponField coupon = new CouponField(checkout);
        PriceLabel price = new PriceLabel(checkout);
        PayButton pay = new PayButton(checkout);
        checkout.register(seats, snacks, coupon, price, pay);

        pay.click();                         // disabled: nothing happens
        seats.select(1);
        coupon.enter("FRIENDS100");          // group coupon, needs 2 seats
        seats.select(2);
        coupon.enter("FRIENDS100");
        snacks.add(1);
        seats.select(1);                     // coupon no longer valid
        pay.click();
    }
}

// ---------------- BEFORE: widgets wired directly to each other ----------------
final class OldPriceLabel {
    String text = "";

    void show(int amount) {
        text = "Total " + amount;
    }
}

final class OldSeatPicker {
    private final OldPriceLabel price;   // plus pay button, coupon field, ...

    OldSeatPicker(OldPriceLabel price) {
        this.price = price;
    }

    void select(int n) {
        price.show(n * 250);             // a pricing rule hidden inside a seat widget
    }
}

// ---------------- AFTER: the Mediator pattern ----------------
interface CheckoutMediator {
    void changed(Widget source);
}

/** Abstract colleague: knows only the mediator interface. */
abstract class Widget {
    private final CheckoutMediator mediator;

    Widget(CheckoutMediator mediator) {
        this.mediator = mediator;
    }

    protected final void changed() {
        mediator.changed(this);
    }
}

final class SeatPicker extends Widget {
    private int seats;

    SeatPicker(CheckoutMediator m) {
        super(m);
    }

    void select(int count) {
        seats = count;
        System.out.println("> user picks " + count + " seat(s)");
        changed();
    }

    int seats() {
        return seats;
    }
}

final class SnackPicker extends Widget {
    private int combos;

    SnackPicker(CheckoutMediator m) {
        super(m);
    }

    void add(int count) {
        combos += count;
        System.out.println("> user adds " + count + " snack combo(s)");
        changed();
    }

    int combos() {
        return combos;
    }
}

final class CouponField extends Widget {
    private String code = "";

    CouponField(CheckoutMediator m) {
        super(m);
    }

    void enter(String newCode) {
        code = newCode;
        System.out.println("> user enters coupon " + newCode);
        changed();
    }

    /** Called by the mediator. Does NOT call changed(), so no update loop. */
    void reject(String reason) {
        System.out.println("  coupon " + code + " rejected: " + reason);
        code = "";
    }

    String code() {
        return code;
    }
}

final class PriceLabel extends Widget {
    PriceLabel(CheckoutMediator m) {
        super(m);
    }

    void show(int total) {
        System.out.println("  price label: " + total);
    }
}

final class PayButton extends Widget {
    private boolean enabled;

    PayButton(CheckoutMediator m) {
        super(m);
    }

    void setEnabled(boolean on) {
        enabled = on;
    }

    void click() {
        if (!enabled) {
            System.out.println("> pay clicked while disabled: ignored");
            return;
        }
        changed();
    }
}

/** Concrete mediator: the only class that knows every widget and the rules between them. */
final class TicketCheckout implements CheckoutMediator {
    private static final int SEAT = 250;
    private static final int COMBO = 180;
    private static final String GROUP_COUPON = "FRIENDS100";

    private SeatPicker seats;
    private SnackPicker snacks;
    private CouponField coupon;
    private PriceLabel price;
    private PayButton pay;
    private int total;

    void register(SeatPicker s, SnackPicker k, CouponField c, PriceLabel p, PayButton b) {
        seats = s;
        snacks = k;
        coupon = c;
        price = p;
        pay = b;
    }

    @Override
    public void changed(Widget source) {
        if (source == pay) {
            System.out.println("  BOOKED " + seats.seats() + " seat(s), " + snacks.combos()
                    + " combo(s), paid " + total);
            return;
        }
        String code = coupon.code();
        if (!code.isEmpty() && !code.equals(GROUP_COUPON)) {
            coupon.reject("unknown code");
        } else if (code.equals(GROUP_COUPON) && seats.seats() < 2) {
            coupon.reject("needs 2+ seats");
        }
        int discount = coupon.code().equals(GROUP_COUPON) ? 100 : 0;
        total = seats.seats() * SEAT + snacks.combos() * COMBO - discount;
        price.show(total);
        pay.setEnabled(seats.seats() > 0);
    }
}

Notes

The problem

Here is the naive design. The seat picker holds the price label, the pay button and the coupon field, and calls each of them. The snack picker also holds the price label. The coupon field needs the seat count. With five parts, there can be up to twenty one-way links. Add a gift card field and you touch almost every class. None of these widgets can be reused on another screen, because each one drags its neighbours along.

Look inside the old seat picker. It knows the seat price, it decides when the pay button is enabled, and it knows that a group coupon needs two seats. Those are checkout rules, not seat picking rules. The same rules are also spread over the snack picker and the coupon field. To answer a simple question, when is the pay button on, you must read three classes.

Tangled SeatPicker
class OldSeatPicker {
  OldPriceLabel price;
  OldPayButton pay;
  OldCouponField coupon;
  void select(int n) {
    price.show(n * 250);
    pay.setEnabled(n > 0);
    if (n < 2) coupon.clear();
  }
}

The idea

The idea: objects stop talking to each other. Each one only tells a mediator that something changed in it. The mediator holds the rules about how the parts work together, and tells the others what to do. The tangle becomes a star. Five widgets now need five links to the centre instead of up to twenty links between them, and every interaction rule lives in one class.

Mediator
  • objects do not talk to each
  • other directly
  • each one tells a mediator
  • "something changed in me"
  • the mediator holds the rules
  • and tells the others what
  • to do
  • many to many becomes one to many

Participants

The participants with our names. Checkout mediator is the interface, with one method: changed. Ticket checkout is the concrete mediator, which knows every widget and holds the rules. Widget is the abstract colleague: it keeps a reference to the mediator interface. Seat picker, snack picker, coupon field, price label and pay button are the concrete colleagues. Notice that a colleague only knows the interface, never the other colleagues.

A colleague

Here is a colleague. Widget holds the mediator and offers one helper, changed, which passes itself to the mediator. Seat picker stores the new seat count and calls changed. That is all. It does not know a price exists, or a coupon, or a pay button. You could drop this seat picker into a concert booking screen with a different mediator and it would just work.

Widget and SeatPicker
abstract class Widget {
  private final CheckoutMediator mediator;
  protected final void changed() {
    mediator.changed(this); }
}
final class SeatPicker extends Widget {
  private int seats;
  void select(int count) {
    seats = count;
    changed();  // tell the mediator
  } }

The mediator

Here is the mediator. Changed receives the widget that spoke. If it was the pay button, it books the tickets. Otherwise it checks the coupon rule: a group coupon needs at least two seats, so it rejects the coupon if not. Then it computes the total from seats, snack combos and the discount, updates the price label and switches the pay button on only when at least one seat is chosen. Every rule is in one readable place.

TicketCheckout.changed()
public void changed(Widget source) {
  if (source == pay) { book(); return; }
  if (groupCoupon() && seats.seats() < 2)
    coupon.reject("needs 2+ seats");
  int total = seats.seats() * SEAT
      + snacks.combos() * COMBO
      - discount();
  price.show(total);
  pay.setEnabled(seats.seats() > 0);
}

One run

Follow one change. The user had two seats, one snack combo and the group coupon, friends one hundred. They drop to one seat. The seat picker tells the mediator. The mediator sees the group coupon no longer applies and rejects it, so the coupon field shows a message. It recomputes the total, two hundred and fifty for the seat plus one hundred and eighty for the combo, four hundred and thirty, and keeps the pay button on.

Both directions

Traffic flows both ways. When the pay button is clicked, it reports to the mediator like any other widget. The mediator reads the seat count and the snack count, books the order and tells the pay button it is done. The pay button never asked the seat picker anything. Colleagues report upwards, and the mediator reads from them and gives commands downwards.

What you gain

What do you gain? Colleagues become small and reusable, because they no longer know their neighbours. The interaction rules are in one class, so you can read them and change them in one place. Adding a gift card field means one new colleague and a few lines in the mediator. And you can test the rules by driving fake widgets, with no real screen at all.

Benefits
  • colleagues are small and
  • reusable on other screens
  • interaction rules are in
  • one class, easy to read
  • add a widget: change the
  • mediator, not five classes
  • test the rules with fake
  • widgets, no real screen
  • links: n instead of n x n

The god mediator

The big risk is a god mediator. The complexity does not vanish, it moves into the middle, and it can grow into a two thousand line class that knows everything. Keep it lean. Use one mediator per feature or per section of the screen. Keep logic that belongs to one widget inside that widget. And let the mediator coordinate, while real calculations, like pricing, live in their own classes that it calls.

Keep the mediator lean
  • risk: every rule of the
  • whole screen in one class
  • fixes:
  • one mediator per feature
  • or per screen section
  • keep widget logic inside
  • the widget
  • mediator only coordinates,
  • it does not compute prices

When to use it

Use a mediator when several objects react to each other in many-to-many ways, when you want to reuse those objects elsewhere, or when the rules between them change often. Skip it when only two or three objects talk, or when the flow is one way. A direct call or a simple listener is clearer there. Adding a coordinator between two objects is just extra indirection.

Use it / skip it
  • use it when:
  • many objects react to each
  • other in tangled ways
  • you want to reuse the parts
  • rules change often
  • skip it when:
  • only two or three objects
  • the flow is one-way: use
  • Observer or a direct call

Neighbours

Compare it with its neighbours. In Observer, a subject broadcasts an event and does not care what the listeners do. It is one to many and one way. A facade is a simple front door for outside callers, and the classes behind it never call the facade. A mediator sits among peers: they talk to it and it talks back, and it owns the rules between them. In practice a mediator often uses observer style events to hear from colleagues.

How it differs
  • Observer: subject broadcasts,
  • does not know what listeners
  • do; one-to-many, one way
  • Facade: a simple front door
  • for outside callers; the
  • subsystem never calls it
  • Mediator: colleagues talk
  • both ways with it, and it
  • holds the rules between them

In practice

The Java standard library has no class called mediator, but the shape is everywhere. A screen controller that wires form widgets together is a mediator. So is an MVC controller sitting between the view and the model, or a match manager in a game between players and the board. At system scale, a message broker or a workflow orchestrator plays the same role between services, so they do not call each other directly.

Where you see the shape
  • UI: a screen controller that
  • wires form widgets together
  • MVC: the controller between
  • view and model
  • games: a match manager
  • between players and board
  • systems: a message broker or
  • workflow orchestrator
  • between services

In LLD interviews

In interviews, look for many peers that must coordinate through one place. In an elevator system, a dispatcher sits between floor buttons and elevator cars, so cars never talk to each other. A group chat room relays messages between users. A control tower assigns runways to planes. An auctioneer stands between bidders. When you draw the dispatcher, say it is a mediator, and say how you keep it from becoming a god class.

Where it shows up
  • elevator: dispatcher between
  • floor buttons and cars
  • group chat: room relays
  • messages between users
  • airport: a control tower
  • assigns runways
  • auction: auctioneer between
  • bidders
  • smart home hub

Common mistakes

Common mistakes. Event loops: the mediator updates the coupon field, the coupon field fires changed again, and the two call each other forever. Commands from the mediator should not trigger new events. Colleagues that still keep references to each other, so the tangle quietly returns. One global mediator for the whole app. And business logic inside the mediator that belongs in model classes.

Avoid these
  • mediator updates a widget,
  • widget fires changed()
  • again: endless loop
  • colleagues still hold refs
  • to each other
  • one global mediator for
  • the whole app
  • business logic inside the
  • mediator instead of models

Interview questions

What problem does the Mediator pattern solve?

It removes direct many-to-many dependencies between objects. Instead of each object calling several others, every object talks only to a mediator that holds the interaction rules, which makes the objects simpler and reusable.

What are the participants of the Mediator pattern?

A mediator interface, a concrete mediator that knows the colleagues and holds the coordination logic, and colleague classes that keep a reference to the mediator and report their changes to it instead of calling each other.

How is Mediator different from Observer?

In Observer, a subject broadcasts events to listeners it does not know in detail, and the flow is one way. A mediator knows its colleagues, receives messages from them and sends commands back, and owns the rules between them. A mediator may use observer-style events internally.

How is Mediator different from Facade?

A facade gives outside clients a simpler interface to a subsystem, and the subsystem classes do not know the facade exists. A mediator coordinates peers that all know it and talk to it in both directions.

What is the main drawback of the Mediator pattern?

The mediator can turn into a god object that holds every rule and becomes hard to change. Split it per feature or screen, keep logic that belongs to one colleague inside that colleague, and move calculations into separate classes.

Where would you use a mediator in an elevator system design?

A dispatcher or controller receives requests from floor buttons and status from each elevator car and decides which car serves which request. Cars and buttons never talk to each other directly, so new scheduling rules change only the dispatcher.

How do you avoid infinite update loops with a mediator?

Separate user-driven changes, which notify the mediator, from updates made by the mediator, which should only set state without notifying again. A guard flag or distinct methods for programmatic updates keeps the mediator from re-entering itself.

Is the Mediator pattern only for user interfaces?

No. It fits any group of peers that coordinate, such as a match manager in a game, an auction house between bidders, or at system level a message broker or workflow orchestrator between services.