首页 > 解决方案 > 创建一个包含一些常量和其他变量的构建器

问题描述

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()

非常感谢您提出任何建议以使其变得更好

标签: kotlin

解决方案


您可以考虑使用这样的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
}

您可以在此处阅读有关密封类的更多信息。


推荐阅读