gpt4 book ai didi

design-patterns - 抽象工厂和继承 Kotlin

转载 作者:行者123 更新时间:2023-12-02 13:13:01 26 4
gpt4 key购买 nike

我正在尝试围绕 Kotlin 设计模式展开思考。我创建了我的抽象工厂,使用 Kotlin 引用作为起点

interface Plant

class OrangePlant : Plant

class ApplePlant : Plant

abstract class PlantFactory {

abstract fun makePlant(): Plant

companion object {
inline fun <reified T : Plant> createFactory(): PlantFactory =
when (T::class) {
OrangePlant::class -> OrangeFactory()
ApplePlant::class -> AppleFactory()
else -> throw IllegalArgumentException()
}
}
}

class AppleFactory : PlantFactory() {
override fun makePlant(): Plant = ApplePlant()
}

class OrangeFactory : PlantFactory() {
override fun makePlant(): Plant = OrangePlant()

我希望所有工厂实例都继承自我现有的抽象类 Foo .我该怎么做?像这样?我错过了什么?还是我失去了理智而没有意识到?
interface Plant

class OrangePlant : Plant

class ApplePlant : Plant

abstract class PlantFactory {
abstract fun makePlant(foo: Foo): Plant

companion object {
inline fun <reified T : Plant> createFactory(): PlantFactory = when (T::class) {
OrangePlant::class -> OrangeFactory()
ApplePlant::class -> AppleFactory()
else -> throw IllegalArgumentException()
}
}
}

class AppleFactory : PlantFactory() {
override fun makePlant(): Plant = ApplePlant()
}

class OrangeFactory : PlantFactory() {
override fun makePlant(): Plant = OrangePlant()
}

还是我应该寻找添加到伴随对象中?

最佳答案

对于继承,你应该简单地说

abstract class PlantFactory : Foo() { ... }

这将使 PlantFactory类型继承自 Foo基类。和你以前的没有区别。

我推荐使用 companion object实现工厂。它使代码缩短:
interface Foo

interface Plant

class OrangePlant : Plant {
companion object Factory : PlantFactory() {
override fun makePlant() = OrangePlant()
}
}

class ApplePlant : Plant {
companion object Factory : PlantFactory() {
override fun makePlant() = ApplePlant()
}
}

abstract class PlantFactory : Foo {
abstract fun makePlant(): Plant
}

fun main(args: Array<String>) {

val foo1 : PlantFactory = OrangePlant.Factory
val foo2 : PlantFactory = ApplePlant.Factory

val orange = foo1.makePlant()
val apple = foo2.makePlant()
}


另外,我删除了 inline fun <reified T : Plant> createFactory(): : 而不是说 PlantFactory.createFactory<OrangePlant>你可以说 OrangePlant.Factory .

你可能仍然有这种方法,在我的情况下,它会有点不同:
inline fun <reified T : Plant> createFactory(): PlantFactory = when (T::class) {
OrangePlant::class -> OrangePlant.Factory
ApplePlant::class -> ApplePlant.Factory
else -> throw IllegalArgumentException()
}

对于类型化的层次结构,使用 sealed 可能是有意义的。类。 Kotlin 将允许写入 when没有 else 的表达式声明是否涵盖所有子类

关于design-patterns - 抽象工厂和继承 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54520330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com