Mediator
- Intent
- Put a go-between in the middle of a group of objects that need to coordinate, so each one only talks to it and the rules of how they work together live in one place.
- Application
- During class, the timer, the finish line, the music and the screen have to stay in step. Have them talk through a single piece that decides what each one does, instead of all of them knowing each other.
WiredFinishLine, highlighted in red, asks WiredTimer isRunning(), calls showFinish() on the screen and cue("bell") on the music.
WiredTimer and WiredFinishLine, highlighted in red, call each other, and each also calls the music and the screen.
ClassFloor appears, highlighted, in the middle of the four devices.
WodTimer and FinishLine, highlighted, report to ClassFloor with timerStarted() and athleteFinished().
ClassFloor, highlighted, tells the music to play, cue or stop, and the screen to show the clock, each time or the results.
FinishLine reports Ana 185 s to ClassFloor, highlighted together with the screen; ClassFloor shows Ana 3:05 on the screen and asks the music for the bell.
POST /api/floor/finish travels from the coach to the controller, finish("Ana", 185) to FinishLine, athleteFinished() to ClassFloor, highlighted, and Ana 3:05 to the screen.
Inside the Spring context, DispatcherServlet, highlighted, asks the HandlerMapping which handler it is, asks the HandlerAdapter to call finish() and, when it fails, the HandlerExceptionResolver answers 400.
Final view: the coach, the controller, the timer, the finish line, ClassFloor, the music and the screen, all inside the Spring context.
Step 1 of 9
Devices that know each other
There are four devices in class: the timer, the finish line where each athlete records their time, the music and the screen. They have to stay in step: at the start the music goes up and the screen shows the clock; when someone finishes, their time shows up and the bell rings; at the cap, the music stops and the results show up.
In the first version, each device calls the others. WiredFinishLine, when recording a time, asks the timer whether it's running, writes on the screen and asks the music for the bell.
Step 2 of 9
A web of dependencies
And the timer, at the cap, asks the finish line for the results to pass them to the screen: the two know each other. Between the four devices there are already six direct calls, and every new device (some lights, a team scoreboard) adds more with whichever ones it has to coordinate with.
To test the finish line you need a timer, a music system and a screen. And to change what happens when someone finishes, you have to find which device it's written in.
Step 3 of 9
One in the middle
Mediator puts a piece in the middle: FloorMediator. The devices just report what happened:
timerStarted(), the timer has started;athleteFinished(...), someone crossed the line;capReached(), time is up.
What each one has to do next is the mediator's decision.
Step 4 of 9
The devices just report
WodTimer no longer knows the music or the screen. start() does a single thing: tell the mediator. FinishLine too: it validates the time and reports with athleteFinished(...).
Music and Screen do what they're told (play, show) and don't know a timer exists. The timer and the finish line are tested with a fake mediator (DevicesTest does it), and the music and the screen with no mediator at all.
Step 5 of 9
The rules, together
ClassFloor is the concrete mediator. Every class rule is in one place:
- at the start: music at 8 and the clock on the screen;
- when someone finishes: it checks the WOD is running and that person hadn't finished already, shows their time and rings the bell;
- at the cap: it stops the music and shows the sorted results.
If a rule changes tomorrow, you know where it is.
Step 6 of 9
A whole class
The test runs a whole class: the timer starts, Ana finishes in 3:05, Leo in 2:52 and the cap arrives. At the end, the music has played, rung two bells and stopped, and the screen shows "1. Leo 2:52" and "2. Ana 3:05".
Neither the timer nor the finish line knows any of that. They just reported.
Step 7 of 9
From the coach's tablet
Each button on the tablet talks to one device: POST /api/floor/start to the timer, POST /api/floor/finish to the finish line and POST /api/floor/cap to the timer again. GET /api/floor/screen reads the screen.
In Spring, ClassFloor is a bean that gets the music and the screen, and the timer and the finish line get FloorMediator. Reports only go one way, towards the mediator, so there are no circular dependencies. If a device had to both report and take orders, you'd have to break the cycle, for example by registering it with the mediator after it's created.
If someone records a time before the start, the answer is 409 with the reason the mediator gives.
Step 8 of 9
Spring already does it for you
To the outside, the DispatcherServlet is a front controller: the single way in for requests. On the inside, it acts as the mediator between Spring MVC's parts, which don't know each other:
- a
HandlerMappingsays which handler serves the URL; - a
HandlerAdapterknows how to call it; - if it fails, a
HandlerExceptionResolverdecides the answer (here,ExceptionHandlerExceptionResolver, which calls our@RestControllerAdvice).
The DispatcherServlet asks them in order and passes one's result on to the next. The test checks each step: which handler was picked, which method was called, which exception the resolver got and the final answer, a 400.
Step 9 of 9
Recap
You started with devices calling each other and ended up with:
- A mediator,
ClassFloor, holding every class rule. - Devices that only report (timer, finish line) or only obey (music, screen).
- No dependencies between devices: each one is tested on its own.
Don't mix it up with its neighbours: with Observer, whoever reports doesn't know who's listening or what they'll do, and nobody coordinates; here the mediator holds that logic. A Facade simplifies access to several parts from outside, but those parts don't use it to talk to each other.
And when you don't need it: if only two pieces talk, letting them know each other is simpler; if the devices only announce "something happened" and there are no rules crossing between them, Observer or Spring events are enough; and watch that the mediator doesn't end up knowing how to do everyone's job.
Code
WiredFinishLine.java
public void finish(String athlete, int seconds) {
if (!timer.isRunning()) { // asks the timer
throw new IllegalStateException("the WOD hasn't started");
}
names.add(athlete);
times.add(new int[] {seconds, names.size() - 1});
screen.showFinish(athlete, Times.format(seconds)); // drives the screen
music.cue("bell"); // and the music
}WiredTimer.java
public void cap() {
running = false;
music.stop();
screen.showResults(finishLine.results()); // the timer reaches into the finish line
}FloorMediator.java
/** The mediator: devices tell it what happened; it decides what everyone else does. */
public interface FloorMediator {
void timerStarted();
void athleteFinished(String athlete, int seconds);
void capReached();
}WodTimer.java
public void start() {
floor.timerStarted(); // no music, no screen: just "I started"
}
public void cap() {
floor.capReached();
}ClassFloor.java
@Override
public synchronized void timerStarted() {
if (running) throw new FloorRuleException("the WOD is already running");
running = true;
finishes.clear();
music.play(8);
screen.showClock();
}
@Override
public synchronized void athleteFinished(String athlete, int seconds) {
if (!running) throw new FloorRuleException("the WOD hasn't started");
String key = athlete.toLowerCase(Locale.ROOT);
if (finishes.containsKey(key)) {
throw new FloorRuleException(finishes.get(key).athlete() + " already finished");
}
finishes.put(key, new Finish(athlete, seconds));
screen.showFinish(athlete, Times.format(seconds));
music.cue("bell");
}
@Override
public synchronized void capReached() {
if (!running) throw new FloorRuleException("the WOD hasn't started");
running = false;
music.stop();
screen.showResults(results());
}ClassFloorTest.java
timer.start(); // music up, clock on the screen
finishLine.finish("Ana", 185); // her time on the screen, the bell rings
finishLine.finish("Leo", 172);
timer.cap(); // music off, results on the screenFloorApiTest.java
mvc.perform(post("/api/floor/start")).andExpect(status().isOk());
mvc.perform(post("/api/floor/finish").contentType(MediaType.APPLICATION_JSON)
.content("{\"athlete\":\"Ana\",\"seconds\":185}"))
.andExpect(status().isOk());
mvc.perform(post("/api/floor/cap")).andExpect(status().isOk());
mvc.perform(get("/api/floor/screen")).andExpect(jsonPath("$[0]").value("1. Ana 3:05"));SpringDoesItTooTest.java
mvc.perform(post("/api/floor/finish").contentType(MediaType.APPLICATION_JSON)
.content("{\"athlete\":\" \",\"seconds\":185}"))
.andExpect(handler().handlerType(FloorController.class)) // a HandlerMapping found the handler
.andExpect(handler().methodName("finish")) // a HandlerAdapter called it
.andExpect(r -> assertThat(r.getResolvedException()) // a HandlerExceptionResolver took the failure
.isInstanceOf(InvalidFinishException.class))
.andExpect(status().isBadRequest()); // …and turned it into the answerFloorMediator.java
/** The mediator: devices tell it what happened; it decides what everyone else does. */
public interface FloorMediator {
void timerStarted();
void athleteFinished(String athlete, int seconds);
void capReached();
}