您的位置 首页 java

Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

码个蛋(codeegg) 第 859 次推文

作者:超凶的土拨鼠

链接:

码妞看世界

Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

Reminder from the book

Java 中,通常的解决可选构造参数的方式是使用可伸缩构造器(telescoping constructor)。当使用可伸缩构造器时,需要为每种不同的参数集合定义构造方法,比如:

 // Kotlin 

class Dialog constructor(
val title: String,
val text: String?,
val onAccept: ( -> Unit)?
) {
constructor(title: String, text: String)
: this(title, text, )
constructor(title: String)
: this(title, "")
}
// Usage
val dialog1 = Dialog("Some title", "Great dialog", { toast("I was clicked") })
val dialog2 = Dialog("Another dialog","I have no buttons")
val dialog3 = Dialog("Dialog with just a title")

非常流行的Android的例子是how we define custom views()

尽管可伸缩构造器在JVM世界很流行, Effective Java 认为对于较大较复杂的类应该使用构建者模式( build er pattern)。构建者模式首先以一种可读性较强的方式收集参数,然后对参数进行校验,最后实例化对象:

 class Dialog private constructor( 

val title: String,
val text: String?,
val onAccept: ( -> Unit)?
) {
class Builder(val title: String) {
var text: String? =
var onAccept: ( -> Unit)? =
fun setText(text: String?): Builder {
this.text = text
return this
}
fun setOnAccept(onAccept: ( -> Unit)?): Builder {
this.onAccept = onAccept
return this
}
fun build = Dialog(title, text, onAccept)
}
}
// Usage
val dialog1 = Dialog.Builder("Some title")
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build
val dialog2 = Dialog.Builder("Another dialog")
.setText("I have no buttons")
.build
val dialog3 = Dialog.Builder("Dialog with just a title").build

尽管构建者模式的声明和使用都较为繁琐,但该模式存在如下优点:

  • 参数很清晰,使用者在设置参数时可以看到每个参数的名字

  • 可以以任何顺序设置参数

  • 修改起来相对可伸缩构造器更为容易

  • 设置好值的Builder可以作为工厂方法使用

Named optional parameters

具名可选参数在大多数情况下是一个更好的选择,相对于构建者模式,具名可选参数的声明和使用都更为简洁,表达能力更强:

 class Dialog( 
val title: String,
val text: String? = ,
val onAccept: ( -> Unit)? =
)
// Usage
val dialog1 = Dialog(
title = "Some title",
text = "Great dialog",
onAccept = { toast("I was clicked") }
)
val dialog2 = Dialog(
title = "Another dialog",
text = "I have no buttons"
)
val dialog3 = Dialog(title = "Dialog with just a title")

使用具名可选参数的构造器拥有构建者模式的大多数优点:

  • 参数很清晰,使用者在设置参数时可以看到每个参数的名字

  • 可以以任何顺序设置参数

  • 修改起来相对可伸缩构造器更为容易(甚至比构建者模式更容易)

但是如果我们希望参数不同时创建不同的变种呢?比如当参数集合不同时创建不同的 dialog

构建者模式:

 interface Dialog { 
fun show
class Builder(val title: String) {
var text: String? =
var onAccept: ( -> Unit)? =
fun setText(text: String?): Builder {
this.text = text
return this
}
fun setOnAccept(onAccept: ( -> Unit)?): Builder {
this.onAccept = onAccept
return this
}
fun build: Dialog = when {
text != && onAccept != ->
TitleTextAcceptationDialog(title, text!!, onAccept!!)
text != ->
TitleTextDialog(title, text!!)
onAccept != ->
TitleAcceptationDialog(title, onAccept!!)
else -> TitleDialog(title)
}
}
}
// Usage
val dialog1 = Dialog.Builder("Some title")
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build
val dialog2 = Dialog.Builder("Another dialog")
.setText("I have no buttons")
.build
val dialog3 = Dialog.Builder("Dialog with just a title").build

我们可以使用具名可选参数的方式来实现吗?当然可以:

 interface Dialog { 
fun show
}
fun makeDialog(
title: String,
text: String? = ,
onAccept: ( -> Unit)?
): Dialog = when {
text != && onAccept != ->
TitleTextAcceptationDialog(title, text, onAccept)
text != ->
TitleTextDialog(title, text)
onAccept != ->
TitleAcceptationDialog(title, onAccept)
else ->
TitleDialog(title)
}
// Usage
val dialog1 = makeDialog(
title = "Some title",
text = "Great dialog",
onAccept = { toast("I was clicked") }
)
val dialog2 = makeDialog(
title = "Another dialog",
text = "I have no buttons"
)
val dialog3 = makeDialog(title = "Dialog with just a title")

同样在这个例子中,我们可以看到具名可选参数相对构建者的优点:

  • 更短 –构造器或工厂方法要比构建者更容易实现。不需要声明属性的名字4次(分别在属性、方法、参数、构造器中);不需要声明属性的类型3次(分别在属性、参数、构造器中)。这是很重要的一点,因为当我们需要修改时,只需修改一处就可以了

  • 更干净 –当你想要知道实例是如何被构建的,只需要查看一个方法即可,而不是整个Builder类。实例被如何持有?如何交互?这些问题在Builder较大时并没有那么明显

  • 不会出现并发问题 –这是一个比较少见的问题,Kotlin中函数参数时immutable的,而Builder类中的属性是mut的,因此使用构建者模式更难实现线程安全

一个使用构建者模式的优点是,设置完参数的Builder可以作为工厂使用,但由于这种情况使用比较少,所有该优点不是很突出。

Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

另外一个关于构建者模式的讨论是,可以对Builder设置部分参数,然后将Builder传递出去。这种情况下我们就可以定义方法创建不完全设置的Builder,交由方法的调用者继续设置。如果想要使用构造器或工厂方法达到相似的效果,我们需要使用自动柯里化(Auto-currying),这在Kotlin中是有可能实现的。

大部分情况下,你应该 优先考虑使用具名可选参数 而不是构建者模式。

D SL for object construction

如果我们想要设置具有多个处理函数(handler)的监听者(listener)。经典的Java做法:

 taskNameView.addTextChangedListener(object : TextWatcher { 
override fun after TextChanged(s: Editable?) {
// ...
}
override fun beforeTextChanged(s: CharSequence?, start : Int, count: Int, after: Int) {
// ...
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// no-op
}
})

这种方式并不是十分的方便,我们可以简单地使用带有具名可选参数的工厂方法取代:

 fun makeTextWatcher( 
afterTextChanged: ((s: Editable?) -> Unit)? = ,
beforeTextChanged: ((s: CharSequence?, start: Int, count: Int, after: Int) -> Unit)? = ,
onTextChanged: ((s: CharSequence?, start: Int, before: Int, count: Int) -> Unit)? =
) = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
afterTextChanged?.invoke(s)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
beforeTextChanged?.invoke(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged?.invoke(s, start, before, count)
}
}
// Usage
taskNameView.addTextChangedListener(makeTextWatcher(
afterTextChanged = { s ->
// ..
},
beforeTextChanged = { s, start, count, after ->
// ...
}
))

或者可以为 TextView 添加一个扩展方法:

 taskNameView.addTextChangedListener( 
afterTextChanged = { s ->
// ..
},
beforeTextChanged = { s, start, count, after ->
// ...
}
)

假设我们使用一个由库提供的 dialog ,库为 dialog 提供了一个Builder作为创建方法:

 val dialog1 = Dialog.Builder("Some title") 
.setText("Great dialog")
.setOnAccept { toast("I was clicked") }
.build

我们可以实现非常简单的DSL Builder:

 fun Dialog(title: String, init: Dialog.Builder.->Unit) = 
Dialog.Builder(title).apply(init).build
// Usage
val dialog1 = Dialog("Some title") {
text = "Great dialog"
setOnAccept { toast("I was clicked") }
}

(我们可以像设置属性一样设置 text ,前提是Builder使用Java定义的)

这种方式下我们利用的DSL的优势同时保留的较为简洁的定义。同时展示了DSL和构建者模式具有很多共同之处。

Summary

Effectiva Java 中的观点在Kotlin中依旧有效。但是在Kotlin中我们拥有更有效的方式–具名可选参数。

看完今天你内容,你觉得什么是构建者?

文章来源:智云一二三科技

文章标题:Effective Java in Kotlin:2. 遇到多个构造器参数时,考虑用构建者

文章地址:https://www.zhihuclub.com/182073.shtml

关于作者: 智云科技

热门文章

网站地图