Merge pull request #6454 from denis-zhdanov/BAEL-2582-kotlin-delegation
BAEL-2581 Delegation Pattern in Kotlin
This commit is contained in:
commit
123a0a4fae
|
@ -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
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue