代码之家  ›  专栏  ›  技术社区  ›  Isaac Manzi

抽象类以实例化另一个已实现的抽象类

  •  0
  • Isaac Manzi  · 技术社区  · 7 年前

    所以我想用libgdx制作一个游戏,所以我的代码有点混乱,所以我将在这里简化它。基本上我有一个抽象类武器,和一个抽象类子弹。在武器类中,应该有一个弹头区域。我该怎么办?这样射击方法就可以创建正确子弹的实例。

    另外,如果我要在抽象项目符号类中创建一个静态列表,并将每个实例添加到其中,这是否有效?或者它会针对每个不同的已实现项目符号进行更改?

    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);   
        }    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   bitbrain    7 年前

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

    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 )这将您的逻辑模型与实际物理或呈现代码分开。确保向武器构造者添加更多的参数来描述是什么使你的武器与其他武器不同或独特。然后可以在 射击() 方法使用提供的属性激发项目符号。