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
作为参数
https://stackoverflow.com/questions/52248742
复制相似问题