Motivation: A set of objects interact in complex ways, creating a web of direct dependencies that is hard to understand and modify. The Mediator design pattern implements the Publisher Subscriber Model architectural style.

Intent: Define an object that encapsulates how a set of objects interact, promoting loose coupling by preventing objects from referring to each other directly.

Here, all components communicate through the mediator which reduces the number of direct connections making the system easier to maintain and extend.

class ChatRoom {
    private val users = mutableListOf<User>()
    fun join(user: User) { users.add(user) }
    fun send(message: String, from: User) {
        users.filter { it != from }.forEach { it.receive(message) }
    }
}
 
class User(val name: String, private val room: ChatRoom) {
    fun send(message: String) = room.send(message, this)
    fun receive(message: String) { println("$name received: $message") }
}