Kotlin 自帶的Builder建造者模式

Kotlin自帶Builder建造者模式,再也不用像Java中,寫那麼多代碼了,必須點贊 !!!
接下來我們來看下如何使用。

方式一

首先,我們新建一個類

class Person {
    var name = ""
    var age = 0
    var married = false

    override fun toString(): String {
        return "Person(name='$name', age=$age, married=$married)"
    }
}

然後,進行調用

val person = Person().apply {
    name = "zhk"
    age = 18
    married = false
}
Log.i("Test", person.toString())

運行程序,可以看到日誌

I/Test: Person(name='zhk', age=18, married=false)

apply: 在kotlin中被叫做一種作用域函數

方式二

新建一個類

class MyDialog {
    var title = ""
    var content = ""

	//這裏使用了 內聯函數(inline) 以避免lambda的額外開銷。
    inline fun show(func: MyDialog.() -> Unit) {
        this.func()
        this.show()
    }

    fun show(){
        //...
    }
}

然後進行調用

MyDialog().show {
   title = "標題"
   content = "內容XXXX"
}

這種方式在kotlin中被稱作DSL回調

方式三

新建一個類

class MyDialog {
    private var tvTitle: TextView? = null
    private var tvContent: TextView? = null

    init {
        val layoutInflater = LayoutInflater.from(Global.getContext())
        val rootView = layoutInflater.inflate(R.layout.dialog_avatar,null)
        tvTitle = rootView.findViewById(R.id.tv_title)
        tvContent = rootView.findViewById(R.id.tv_content)
        //...
    }

    fun title(@StringRes res: Int? = null, text: CharSequence? = null): MyDialog {
        if (res != null) {
            this.tvTitle?.text = Global.getContext().getString(res)
        } else if (text != null) {
            this.tvTitle?.text = text
        }
        return this
    }

    fun content(@StringRes res: Int? = null, text: CharSequence? = null): MyDialog {
        if (res != null) {
            this.tvContent?.text = Global.getContext().getString(res)
        } else if (text != null) {
            this.tvContent?.text = text
        }
        return this
    }

	//這裏使用了 內聯函數(inline) 以避免lambda的額外開銷。
    inline fun show(func: MyDialog.() -> Unit) {
        this.func()
        this.show()
    }

    fun show() {
        //...
    }
}

進行調用

MyDialog().show {
    title(res = R.string.login_title)
    content(text = "內容XXXX")
}

可以自行選擇傳入res或text,並且可以控制傳參,做一些額外操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章