Android-Build模式

Build模式在Android中非常常见,例如dialog创建、okhttp配置等等。build模式是将复杂对象和表示分离,一步步构造对象。

1、静态内部类Build中function setConponent()将各个属性设置进去并返回this

2、build()创建Product(build), 参数构造时将build属性设置给product

3、Product.Build().setConponent().build创建product instance

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
//Build模式
class Product() {
private lateinit var head: String
private lateinit var body: String
private lateinit var foot: String

constructor(build: Build) : this() {
this.head = build.head
this.body = build.body
this.foot = build.foot
}

override fun toString(): String {
return ("Product: head $head body$body foot$foot")
}


class Build {
lateinit var head: String
lateinit var body: String
lateinit var foot: String

fun setHead(head: String): Build {
this.head = head
return this
}

fun setBody(body: String): Build {
this.body = body
return this
}

fun setFoot(foot: String): Build {
this.foot = foot
return this
}

fun build(): Product {
return Product(this)
}
}
}

fun main() {
var product = Product.Build()
.setHead("yeah I'm head").setBody(" now is body").setFoot(" atlast foot").build()
println(product.toString())
}

Android-Build模式
http://example.com/2021/12/03/Android-Build模式/
作者
xdd
发布于
2021年12月3日
许可协议