【发布时间】:2018-09-10 06:39:18
【问题描述】:
abstract class Fruit {
private content: Fruit[] = [];
addChild() {
// Pick one at random (using this as an example instead of the actual criteria that determines this)
const type = pickOne(['apple', 'banana', 'cherry']);
switch (type) {
case 'apple':
this.content.push(new Apple());
case 'banana':
this.content.push(new Banana());
case 'cherry':
this.content.push(new Cherry());
}
}
}
class Apple extends Fruit { }
class Banana extends Fruit { }
class Cherry extends Fruit { }
如何在不创建循环依赖的情况下对其进行重组,以便:
- 每个类都在一个单独的文件中
-
addChild()方法适用于所有孩子,无需复制代码
我已经读到,基类了解子类的任何信息通常是一种不好的模式,但我不确定更好的模式是什么样的。
Example that might make more sense
编辑:删除 type 作为参数
【问题讨论】:
-
我认为这通常取决于用例。你真的应该考虑一下你可能会遇到什么问题,特别是如果你想改变任何东西。
-
孩子们既是 Fruit 的子类又是其内容的一部分,这似乎很奇怪。你的类不应该是 FruitContainer 并且水果不应该继承自它吗?
-
您的内容数组是否有理由按子类类型拆分,而不仅仅是 Array
? -
@Axnyff 所有水果都可以有一系列嵌套的水果(水果名称实际上没有意义,抱歉)
-
@WilliamOliver 是的,这可能更有意义。我试图表明
Fruit类本身并没有被使用,但将其切换为抽象类更有意义。
标签: javascript node.js typescript