forked from dbacinski/Design-Patterns-In-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Builder.kt
97 lines (74 loc) · 2.35 KB
/
Builder.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import org.junit.jupiter.api.Test
import java.io.File
// Let's assume that Dialog class is provided by external library.
// We have only access to Dialog public interface which cannot be changed.
class Dialog {
fun setTitle(text: String) = println("setting title text $text")
fun setTitleColor(color: String) = println("setting title color $color")
fun setMessage(text: String) = println("setting message $text")
fun setMessageColor(color: String) = println("setting message color $color")
fun setImage(bitmapBytes: ByteArray) = println("setting image with size ${bitmapBytes.size}")
fun show() = println("showing dialog $this")
}
// Builder
class DialogBuilder() {
constructor(init: DialogBuilder.() -> Unit) : this() {
init()
}
private var titleHolder: TextView? = null
private var messageHolder: TextView? = null
private var imageHolder: File? = null
fun title(attributes: TextView.() -> Unit) {
titleHolder = TextView().apply { attributes() }
}
fun message(attributes: TextView.() -> Unit) {
messageHolder = TextView().apply { attributes() }
}
fun image(attributes: () -> File) {
imageHolder = attributes()
}
fun build(): Dialog {
println("build")
val dialog = Dialog()
titleHolder?.apply {
dialog.setTitle(text)
dialog.setTitleColor(color)
}
messageHolder?.apply {
dialog.setMessage(text)
dialog.setMessageColor(color)
}
imageHolder?.apply {
dialog.setImage(readBytes())
}
return dialog
}
class TextView {
var text: String = ""
var color: String = "#00000"
}
}
//Function that creates dialog builder and builds Dialog
fun dialog(init: DialogBuilder.() -> Unit): Dialog =
DialogBuilder(init).build()
class BuilderTest {
@Test
fun Builder() {
println("Build dialog")
val dialog: Dialog =
dialog {
title {
text = "Dialog Title"
}
message {
text = "Dialog Message"
color = "#333333"
}
image {
File.createTempFile("image", "jpg")
}
}
println("Show dialog")
dialog.show()
}
}