kotlin - 创建一个包含一些常量和其他变量的构建器
问题描述
kotlin 1.3.61
我有以下课程,不确定它是否是创建构建器的最佳设计。基本上,销售和产品的图标和背景会有不同的常数。但可以更改标题和描述。可能会添加其他常量,即技术。所以这个类的用户不必担心这个常量是如何创建的。
但标题和地址需要从课堂外提供。在创建我的构建器时,我使用了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
}
您可以在此处阅读有关密封类的更多信息。
推荐阅读
- django - Django:如果对象在带有过滤器的列表中,则使用 manytomany 字段检查模型
- maven - 如何使用 maven 发布插件更新非 pom 文件中的版本
- etl - 列值包含空格时的字段溢出
- javascript - Twilio 聊天连接因服务器错误 406 而关闭
- c - ApplicationName.exe 在 Visual Studio 中触发了断点
- python - 水壶问题没有清空其他两个瓶子
- r - Shiny - 更改 selectInput() 中的选项数量
- r - 如何从R中的其他组中减去一组的值
- windows-installer - 如何在 Visual Studio 中添加 QBFC 作为依赖项
- python - 如何使用硒在 chromedriver 中打开单个选项卡