-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mediator.kt
73 lines (56 loc) · 1.64 KB
/
Mediator.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* Description
*
* The mediator pattern is used to reduce
* coupling between classes that communicate
* with each other. Instead of classes
* communicating directly, and thus requiring
* knowledge of their implementation, the
* classes send messages via a mediator object.
*/
/* Mediator */
interface ChatMediator {
fun addUser(user: ChatUser): ChatMediator
fun sendMessage(user: ChatUser, message: String)
}
/* ConcreteMediator */
class ChatMediatorImpl : ChatMediator {
private val users = mutableListOf<ChatUser>()
override fun addUser(user: ChatUser) = apply {
users.add(user)
}
override fun sendMessage(user: ChatUser, message: String) {
users.filter { it != user }
.forEach { it.receive(message) }
}
}
/* AbstractColleague */
interface Colleague {
fun send(message: String)
fun receive(message: String)
}
/* ConcreteColleague */
class ChatUser(private val mediator: ChatMediator, private val name: String) : Colleague {
override fun send(message: String) {
println("$name sending message: $message")
mediator.sendMessage(this, message)
}
override fun receive(message: String) {
println("$name received message: $message")
}
}
/* Usage */
fun main() {
val chatMediator = ChatMediatorImpl()
val mike = ChatUser(chatMediator, "Mike")
chatMediator
.addUser(mike)
.addUser(ChatUser(chatMediator, "John"))
.addUser(ChatUser(chatMediator, "Alice"))
mike.send("Hello, World!")
}
/* Output
*
* Mike sending message: Hello, World!
* John received message: Hello, World!
* Alice received message: Hello, World!
*/