问题描述
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 { }
如何在不创建循环依赖关系的情况下对其进行重组,以便:
How can I restructure this without creating circular dependencies so that:
- 每个班级都在一个单独的文件中
-
addChild()所有孩子都可以使用code>方法而无需复制代码
- Each class is in a separate file
- The
addChild()
method is available on all children without duplicating the code
我读过它通常是一个糟糕的模式基类知道有关子类的任何内容,但我不确定更好的模式是什么样的。
I've read that it is generally a bad pattern for the base class to know anything about child classes but I'm not sure what a better pattern would look like.
编辑:已移除输入
作为参数
推荐答案
您需要从工厂类中拆分抽象类(创建新实例):
You need to split the abstract class from the factory class (create new instances):
// fruit.ts
abstract class Fruit {
private content: Array<Fruit> = [];
addChild(child: Fruit) {
this.content.push(child);
}
}
// fruit-factory.ts
class FruitFactory {
create(type: 'apple' | 'banana' | 'cherry'): Fruit {
switch (type) {
case 'apple':
return new Apple();
case 'banana':
return new Banana();
case 'cherry':
return new Cherry();
}
}
}
// apple.ts
class Apple extends Fruit { }
// banana.ts
class Banana extends Fruit { }
// cherry.ts
class Cherry extends Fruit { }
对于隔离并重用创建对象的代码。
The Factory design pattern is useful to isolate and reuse the code that creates an object.
在更详细的示例中, loadChildren
不必绑定到 List
抽象类。这使得 List
摘要有3个职责:作为列表,从外部源加载数据以及创建新实体。
In your more detailed example, the loadChildren
does not have to be tied to the List
abstract class. This makes the List
abstract have 3 responsibilities: being a list, loading data from an external source and creating new entities.
可维护代码的指导原则是每个班级都有一个责任。
A guiding principle for maintainable code is the single responsibility principle where each class have a single responsibility.
我建议您拆分列表
对象在3个类中,基于确定的职责:抽象类列表
,类ListFactory
和类DataFetcher
。
I suggest that you split your List
object in 3 classes, based on the identified responsibilities: abstract class List
, class ListFactory
and class DataFetcher
.
这将允许您为每个类定义一个良好的接口。
This will allow you to define a good interface for each of these classes.
这篇关于Javascript:如何在不创建循环依赖项的情况下重用创建子实例的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!