File tree Expand file tree Collapse file tree
main/kotlin/com/baeldung/kotlin/delegates
test/kotlin/com/baeldung/kotlin/delegates Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com.baeldung.kotlin.delegates
2+
3+ import java.util.concurrent.locks.ReentrantLock
4+ import kotlin.concurrent.withLock
5+
6+ interface Producer {
7+
8+ fun produce (): String
9+ }
10+
11+ class ProducerImpl : Producer {
12+
13+ override fun produce () = " ProducerImpl"
14+ }
15+
16+ class EnhancedProducer (private val delegate : Producer ) : Producer by delegate {
17+
18+ override fun produce () = " ${delegate.produce()} and EnhancedProducer"
19+ }
20+
21+ interface MessageService {
22+
23+ fun processMessage (message : String ): String
24+ }
25+
26+ class MessageServiceImpl : MessageService {
27+ override fun processMessage (message : String ): String {
28+ return " MessageServiceImpl: $message "
29+ }
30+ }
31+
32+ interface UserService {
33+
34+ fun processUser (userId : String ): String
35+ }
36+
37+ class UserServiceImpl : UserService {
38+
39+ override fun processUser (userId : String ): String {
40+ return " UserServiceImpl: $userId "
41+ }
42+ }
43+
44+ class CompositeService : UserService by UserServiceImpl (), MessageService by MessageServiceImpl()
45+
46+ interface Service {
47+
48+ val seed: Int
49+
50+ fun serve (action : (Int ) -> Unit )
51+ }
52+
53+ class ServiceImpl : Service {
54+
55+ override val seed = 1
56+
57+ override fun serve (action : (Int ) -> Unit ) {
58+ action(seed)
59+ }
60+ }
61+
62+ class ServiceDecorator : Service by ServiceImpl () {
63+ override val seed = 2
64+ }
Original file line number Diff line number Diff line change 1+ package com.baeldung.kotlin.delegates
2+
3+ import org.assertj.core.api.Assertions.assertThat
4+ import org.junit.Test
5+
6+ class InterfaceDelegationTest {
7+
8+ @Test
9+ fun `when delegated implementation is used then it works as expected` () {
10+ val producer = EnhancedProducer (ProducerImpl ())
11+ assertThat(producer.produce()).isEqualTo(" ProducerImpl and EnhancedProducer" )
12+ }
13+
14+ @Test
15+ fun `when composite delegation is used then it works as expected` () {
16+ val service = CompositeService ()
17+ assertThat(service.processMessage(" message" )).isEqualTo(" MessageServiceImpl: message" )
18+ assertThat(service.processUser(" user" )).isEqualTo(" UserServiceImpl: user" )
19+ }
20+
21+ @Test
22+ fun `when decoration is used then delegate knows nothing about it` () {
23+ val service = ServiceDecorator ()
24+ service.serve {
25+ assertThat(it).isEqualTo(1 )
26+ }
27+ }
28+ }
You can’t perform that action at this time.
0 commit comments