Kotlin Builder模式
阿新 • • 發佈:2018-11-27
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
}