-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mediator.kt
46 lines (34 loc) · 987 Bytes
/
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
import org.junit.jupiter.api.Test
class ChatUser(private val mediator: ChatMediator, val name: String) {
fun send(msg: String) {
println("$name: Sending Message= $msg")
mediator.sendMessage(msg, this)
}
fun receive(msg: String) {
println("$name: Message received: $msg")
}
}
class ChatMediator {
private val users: MutableList<ChatUser> = ArrayList()
fun sendMessage(msg: String, user: ChatUser) {
users
.filter { it != user }
.forEach {
it.receive(msg)
}
}
fun addUser(user: ChatUser): ChatMediator =
apply { users.add(user) }
}
class MediatorTest {
@Test
fun `Mediator`() {
val mediator = ChatMediator()
val john = ChatUser(mediator, "John")
mediator
.addUser(ChatUser(mediator, "Alice"))
.addUser(ChatUser(mediator, "Bob"))
.addUser(john)
john.send("Hi everyone!")
}
}