BAEL-2581 Delegation Pattern in Kotlin

This commit is contained in:
Denis Zhdanov 2019-03-03 07:24:02 +08:00
parent 3cbd70a6e1
commit 47eee45301
2 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,64 @@
package com.baeldung.kotlin.delegates
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
interface Producer {
fun produce(): String
}
class ProducerImpl : Producer {
override fun produce() = "ProducerImpl"
}
class EnhancedProducer(private val delegate: Producer) : Producer by delegate {
override fun produce() = "${delegate.produce()} and EnhancedProducer"
}
interface MessageService {
fun processMessage(message: String): String
}
class MessageServiceImpl : MessageService {
override fun processMessage(message: String): String {
return "MessageServiceImpl: $message"
}
}
interface UserService {
fun processUser(userId: String): String
}
class UserServiceImpl : UserService {
override fun processUser(userId: String): String {
return "UserServiceImpl: $userId"
}
}
class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl()
interface Service {
val seed: Int
fun serve(action: (Int) -> Unit)
}
class ServiceImpl : Service {
override val seed = 1
override fun serve(action: (Int) -> Unit) {
action(seed)
}
}
class ServiceDecorator : Service by ServiceImpl() {
override val seed = 2
}

View File

@ -0,0 +1,28 @@
package com.baeldung.kotlin.delegates
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class InterfaceDelegationTest {
@Test
fun `when delegated implementation is used then it works as expected`() {
val producer = EnhancedProducer(ProducerImpl())
assertThat(producer.produce()).isEqualTo("ProducerImpl and EnhancedProducer")
}
@Test
fun `when composite delegation is used then it works as expected`() {
val service = CompositeService()
assertThat(service.processMessage("message")).isEqualTo("MessageServiceImpl: message")
assertThat(service.processUser("user")).isEqualTo("UserServiceImpl: user")
}
@Test
fun `when decoration is used then delegate knows nothing about it`() {
val service = ServiceDecorator()
service.serve {
assertThat(it).isEqualTo(1)
}
}
}