欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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
        }
相关标签: Kotlin Builder