标签:UI 伴生对象 int 模式 kotlin string struct 一段 .net
Ktolin的可以使用DSL方式来创建对象,那么对于设计模式来说,DSL方式创建对象就类似于Java 中使用Builder对象来创建,那么来一段代码看看DSL方式创建对象吧,当然Java也可以调用的哦!
class UnionBankPay private constructor(val activity: Activity,
val tradeCode: String,
val serverModel: String){
//私有化构造方法
private constructor(builder: Builder) : this(builder.activity,
builder.tradeCode,
builder.serverModel)
//伴生对象,对外提供静态的build方法
companion object {
fun build(init: Builder.() -> Unit) = Builder(init).build()
}
//Builder 内部类
class Builder private constructor() {
constructor(init: Builder.() -> Unit) : this() {
init()
}
//属性
lateinit var activity: Activity
lateinit var tradeCode: String
lateinit var serverModel: String
//DSL赋值方法
fun activity(init: Builder.() -> Activity) = apply { activity = init() }
fun tradeCode(init: Builder.() -> String) = apply { tradeCode = init() }
fun serverModel(init: Builder.() -> String) = apply { serverModel = init() }
fun build() = UnionBankPay(this)
}
}
UnionBankPay.build {
activity { this@MainActivity}
tradeCode { "123123" }
serverModel { "00" }
}
或者
UnionBankPay.build {
activity = this@MainActivity
tradeCode = "123123"
serverModel = "00"
}
标签:UI 伴生对象 int 模式 kotlin string struct 一段 .net
原文地址:http://www.cnblogs.com/gongxiaojiu/p/7028869.html