Kotlin Builder模式
程序员文章站
2022-06-04 17:06:37
...
class Person(var name: String, var age: Int) {
constructor(builder: Builder) : this(builder.name, builder.age)
companion object {
fun builder(): Builder {
return Builder()
}
}
class Builder {
var name: String = ""
var age: Int = 0
fun setName(name: String): Builder {
this.name = name
return this
}
fun setAge(age: Int): Builder {
this.age = age
return this
}
fun build(): Person {
return Person(this)
}
}
}
进阶版(推荐)
class Person(var name: String, var age: Int) {
constructor(builder: Builder) : this(builder.name, builder.age)
companion object {
inline fun build(block: Builder.() -> Unit): Person {
return Builder().apply(block).build()
}
}
class Builder {
var name: String = ""
var age: Int = 0
fun build(): Person {
return Person(this)
}
}
}
调用:
var p1 = Person.build {
name = ""
age = 10
}
上一篇: 一言难尽
下一篇: Adroid 之 Builder 对话框