-
Notifications
You must be signed in to change notification settings - Fork 108
/
Template Method.kt
55 lines (37 loc) · 1.19 KB
/
Template Method.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
47
48
49
50
51
52
53
54
55
package design_patterns
/**
*
* Template method a behavioral design pattern that defines the basis of an algorithm
*
* and allows subclasses to redefine some steps of the algorithm without changing its overall structure
*
*/
data class Cake(
val layers: List<String>,
val cream: String,
val sprinkles: String
)
abstract class CakeBaker {
protected abstract fun layer(): String
protected abstract fun cream(): String
protected abstract fun sprinkles(): String
// we have the basis of an algorithm
fun makeCake(numberOfLayers: Int): Cake {
return Cake(
layers = List(numberOfLayers) { layer() },
cream = cream(),
sprinkles = sprinkles()
)
}
}
class ChocolateCakeBaker : CakeBaker() {
// subclasses redefines some steps of the algorithm
override fun cream(): String = "chocolate cream"
override fun layer(): String = "chocolate cake layer"
override fun sprinkles(): String = "chocolate chips"
}
class WaffleCakeBaker : CakeBaker() {
override fun cream(): String = "custard cream"
override fun layer(): String = "waffle cake layer"
override fun sprinkles(): String = "coconut flakes"
}