我试图实现一种简洁的方法来构建多个工厂(受植物和僵尸的启发)。为了更容易地添加更多的植物类型,我想使工厂的成本和dmg保持不变,这样我就可以为所有这种类型的工厂设置一次。
在这种情况下,我只有一个植物(向日葵),现在我想实例化向日葵植物。在单元格类中的构建方法中。
在这样做时,我得到了一个错误:Cannot create an instance of an abstract class.,这对我来说是可以理解的。那么,是否有一种方法只能将非抽象类作为build()方法的参数从if (!c isAbstract)扩展而来,还是必须实现某种if (!c isAbstract)
abstract class Plant {
public static dmg: number;
public static cost: number;
constructor(cell: Cell) {
this.cell = cell;
}
cell: Cell;
}
// I would like to create more Plants like this
class Sunflower extends Plant {
public static dmg = 0;
public static cost = 50;
cell: Cell;
constructor(cell: Cell) {
super(cell);
}
}
class Cell {
build(c: typeof Plant) {
if (c.cost <= game.money) {
this.plant = new c(this); //Cannot create an instance of an abstract class.
game.money -= c.cost;
}
}
}
// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);发布于 2022-02-09 12:29:22
你可以这样做:
class Cell {
build<T extends Plant>(plant: (new (cell:Cell) => T)) {
const plantInstance = new plant(this);
}
}https://stackoverflow.com/questions/71049493
复制相似问题