kotlin 1.3.61
我有以下类(class),但不确定它是否是创建构建器的最佳设计。基本上,销售和产品的图标和背景会有不同的常量。但是标题和描述可以更改。可能会添加其他常量,即技术常量。所以这个类的用户不必担心这个常量是如何创建的。
但是标题和地址需要从课外提供。在创建我的构建器时,我使用了
copy
更新标题和描述。并且不确定这是否是最好的方法?class Marketing {
data class Model(
val title: String = "",
val description: String = "",
val icon: Int,
val background: Int)
class Builder() {
private var title: String = ""
private var description: String = ""
private val PRODUCT = Model(
icon = 111111,
background = 333333)
private val SALES = Model(
icon = 222222,
background = 444444)
fun title(title: String): Builder {
this.title = title
return this
}
fun description(description: String): Builder {
this.description = description
return this
}
fun buildProduct(): Model {
return PRODUCT.copy(title = title, description = description)
}
fun buildSales(): Model {
return SALES.copy(title = title, description = description)
}
}
}
我是这样使用它的:
val product = Marketing.Builder()
.description("this is the description of the product")
.title("this is the title of the product")
.buildProduct()
val sales = Marketing.Builder()
.description("this is the description of the sales")
.title("this is the title of the sales")
.buildSales()
如您所见,通过调用适当的构建器(即
buildProduct()
)可以轻松创建不同的产品。和 buildSales()
非常感谢您的任何建议,以使其更好
最佳答案
您可以考虑使用sealed
像这样的类:
sealed class Model(
open val title: String,
open val description: String,
val icon: Int,
val background: Int
) {
data class Product(override val title: String, override val description: String) :
Model(
title,
description,
111111,
333333)
data class Sales(override val title: String, override val description: String) :
Model(
title,
description,
111111,
333333)
}
这边走:
Model
))好处:
您可以将实例作为
Model
传递并将所有实例视为相同和/或在 when 子句中检查它们以获取要对其进行操作的正确类型(如果用作表达式,则不需要 else 分支):fun showModel(model: Model){
title.text = model.title
}
或者你可以这样做:
fun doSomething(model: Model) = when (model) {
is Product -> Unit
is Sales -> Unit
}
您可以阅读有关密封类的更多信息 here .
关于kotlin - 使用一些常量和其他变量创建一个构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60143608/