Skip to content

Commit 86a3d3c

Browse files
authored
Merge pull request Kotlin#25 from thomaskempel/master
Add Example for Delegation Pattern
2 parents 9efae91 + c660740 commit 86a3d3c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

_data/examples.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,7 @@
3636
url: destructuring
3737
- title: Sealed Classes
3838
url: sealedClasses
39+
- title: Delegation Pattern
40+
url: delegationPattern
3941

4042

_examples/delegationPattern.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
title: Delegation Pattern
3+
---
4+
5+
<div class="sample" markdown="1">
6+
7+
```kotlin
8+
interface SoundBehaviour { // 1
9+
fun makeSound()
10+
}
11+
12+
class ScreamBehavior(val n:String): SoundBehaviour { // 2
13+
override fun makeSound() = println("${n.toUpperCase()} !!!")
14+
}
15+
16+
class RockAndRollBehavior(val n:String): SoundBehaviour {
17+
override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n") // 2
18+
}
19+
20+
// Tom Araya is the "singer" of Slayer
21+
class TomAraya(n:String): SoundBehaviour by ScreamBehavior(n) // 3
22+
23+
// You should know ;)
24+
class ElvisPresley(n:String): SoundBehaviour by RockAndRollBehavior(n) // 3
25+
26+
fun main(args: Array<String>) {
27+
val tomAraya = TomAraya("Trash Metal!")
28+
tomAraya.makeSound() // 4
29+
val elvisPresley = ElvisPresley("Dancin' to the Jailhouse Rock.")
30+
elvisPresley.makeSound()
31+
}
32+
```
33+
34+
</div>
35+
36+
In Kotlin it's easy to delegate method calls without any boilersplate.
37+
38+
1. The interface SoundBehaviour is defined. Later there will be one class that implements the method and another will also have the interface, but just delegates the method call.
39+
2. The class ScreamBehavior and RockAndRollBehavior actually implement the method.
40+
3. The class TomAraya and ElvisPresley just delegate the methods defined by the interface SoundBehaviour to the responsible implementation. But doesn't need any boilerplate to delegate the method call at all.
41+
4. Call makeSound() on tomAraya of type TomAraya or elvisPresley of type ElvisPresley and it is delegated to the assiciated class

0 commit comments

Comments
 (0)