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:
- 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.
Example that might make more sense
Edit: Removed type as an argument