1. 程式人生 > >(轉載) Kotlin 設計模式-建造者

(轉載) Kotlin 設計模式-建造者

struct href bank show model contain haskell num keyword

前言

Ktolin的可以使用DSL方式來創建對象,那麽對於設計模式來說,DSL方式創建對象就類似於Java 中使用Builder對象來創建,那麽來一段代碼看看DSL方式創建對象吧,當然Java也可以調用的哦!

Show me the Code

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)
    }
}
  • 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
  • 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

調用

UnionBankPay.build {
         activity { this@MainActivity}
         tradeCode { "123123" }
         serverModel { "00" }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

或者

UnionBankPay.build {
    activity = this@MainActivity
    tradeCode = "123123" 
    serverModel = "00" 
}

(轉載) Kotlin 設計模式-建造者