...

/

Mediator Design Pattern

Mediator Design Pattern

Learn how to implement the Mediator design pattern in Kotlin.

The development team of our game has some real problems—and they’re not related to code directly. Let’s imagine we have our little indie company consisting of only me, a canary named Michael that acts as a product manager, and two cat designers that sleep most of the day but produce some decent mockups from time to time. We have no Quality Assurance (QA) whatsoever. Maybe that’s one of the reasons our game keeps crashing all the time.

Recently Michael has introduced us to a parrot named Kenny, who happens to be QA:

interface QA {
fun doesMyCodeWork(): Boolean
}
interface Parrot {
fun isEating(): Boolean
fun isSleeping(): Boolean
}
object Kenny : QA, Parrot {
// Implements interface methods based on parrot
// schedule
}
Kenny, the object that implements QA and Parrot interfaces

The parrot Kenny is a simple object that implements two interfaces: QA, to do QA work, and Parrot, because it’s a parrot.

Parrot QAs are very motivated. They’re ready to test the latest version of our game at any time. But they don’t like to be bothered when they are either sleeping or eating:

object Me
object MyCompany {
val cto = Me
val qa = Kenny
fun taskCompleted() {
if (!qa.isEating() && !qa.isSleeping()) {
println(qa.doesMyCodeWork())
}
}
}
MyCompany object with a CTO and QA, and a taskCompleted() function

In case Kenny has any questions, I gave him my direct number:

object Kenny : ... {
val developer = Me
}
Kenny object with a developer property that refers to Me object

Kenny is a hard-working parrot. But we had so many bugs that we also had to hire a second parrot QA, Brad. If Kenny is free, I give the job to him as he’s more acquainted with our project. But if he’s busy, I check if Brad is free and give the task to him: