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,并且可以控制传参,做一些额外操作。

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