抽象 class 实例化另一个实现的抽象 class

Abstract class to instantiate another implemented abstract class

所以我正在尝试使用 LibGDX 制作游戏,所以我的代码有点乱,所以我会在这里简化它。基本上我有一个抽象 class 武器和抽象 class 子弹。在武器 class 中,应该有一个 Bullet 类型的字段。我该怎么做?这样射击方法就可以创建正确子弹的实例。

此外,如果我要在抽象 Bullet class 中创建一个静态列表并将每个实例添加到其中,这行得通吗?还是会针对每个不同的实施项目符号改变?

public abstract class Weapon {
    public Bullet bullet;
}

public abstract class Bullet { 
    public Vector2 position;
    public Bullet(Vector2 position){
        this.position = position;
    }
}

public Rifle extends Weapon{
    this.bullet = RifleBullet.class;
}

public RifleBullet extends Bullet{
    public RifleBullet(Vector2 start){ 
        super(start);   
    }    
}

我确实建议尽可能避免继承。它只会让您的生活更轻松。相反,做这样的事情:

public class Weapon {
   private final Bullet template;

   public Weapon(Bullet template) {
      this.template = template;
   }
   /* shoot logic here */
}

public class Bullet { 
   private final Vector2 position;
   private final float velocity;
   public Bullet(float speed) {
      this.position = new Vector2();
      this.speed = speed;
   }
   /* setters and getters */
}

这遵循 Composition over Inheritance 原则,可以让您保持代码简单并提供更多控制权:

Bullet rifleBullet = new Bullet(2f);
Weapon rifle = new Weapon(rifleBullet);

Bullet shotgunBullet = new Bullet(5f);
Weapon shotgun = new Weapon(shotgunBullet);

/* somewhere in update() */
shotgun.shoot();
rifle.shoot();

然后 shoot() 方法可以实现实际项目符号的创建(例如使用 libgdx bullets)。这将您的逻辑模型与实际物理或渲染代码分开。确保向武器构造函数添加更多参数,以描述是什么让您的武器与其他武器不同或独特。然后可以在 shoot() 方法中使用此信息,使用提供的属性发射子弹。