-
Notifications
You must be signed in to change notification settings - Fork 103
/
Decorator.kt
50 lines (43 loc) · 1.37 KB
/
Decorator.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
package design_patterns
/**
*
* Decorator is a structural design pattern that adds new functionality to an object:
*
* classes implement a common interface and to extend the functionality of the previous object,
*
* the old object is passed through the constructor
*
*/
interface MyPrinter {
fun printedText() : String
}
// just returns "Hello"
class HelloPrinter : MyPrinter {
override fun printedText() : String {
return "Hello"
}
}
// adds a comma to the previous value of the printedText() function
class CommaPrinter(private val printer: MyPrinter) : MyPrinter {
override fun printedText() : String {
return "${printer.printedText()},"
}
}
// adds a space to the previous value of the printedText() function
class SpacePrinter(private val printer: MyPrinter) : MyPrinter {
override fun printedText() : String {
return "${printer.printedText()} "
}
}
// adds the word "World" to the previous value of the printedText() function
class WorldPrinter(private val printer: MyPrinter) : MyPrinter {
override fun printedText() : String {
return "${printer.printedText()}World"
}
}
// adds an exclamation mark to the previous value of the printedText() function
class ExclamationPrinter(private val printer: MyPrinter) : MyPrinter {
override fun printedText() : String {
return "${printer.printedText()}!"
}
}