kotlin 1.3.61
Run Code Online (Sandbox Code Playgroud)
我有以下课程,不确定它是否是创建构建器的最佳设计。基本上,销售和产品的图标和背景会有不同的常量。但是标题和描述可以更改。可能会添加其他常量,即技术常量。所以这个类的用户不必担心这个常量是如何创建的。
但是标题和地址需要从课外提供。在创建我的构建器时,我使用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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
我是这样使用它的:
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()
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,通过调用适当的构建器 iebuildProduct()
和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)
}
Run Code Online (Sandbox Code Playgroud)
这边走:
Model
)传递它们)好处:
您可以将实例作为传递Model
,并将所有实例视为相同和/或在 when 子句中检查它们以获取要对其进行操作的正确类型(如果用作表达式,则不需要 else 分支):
fun showModel(model: Model){
title.text = model.title
}
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
fun doSomething(model: Model) = when (model) {
is Product -> Unit
is Sales -> Unit
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关密封类的更多信息。
归档时间: |
|
查看次数: |
255 次 |
最近记录: |