簡體   English   中英

抽象類實例化另一個實現的抽象類

[英]Abstract class to instantiate another implemented abstract class

因此,我嘗試使用LibGDX制作游戲,因此我的代碼有點混亂,因此在此我將其簡化。 基本上,我有一個抽象類武器,和一個抽象類子彈。 在武器類別中,應該有一個子彈類型字段。 我該怎么辦? 這樣射擊方法可以創建正確子彈的實例。

另外,如果我要在抽象的Bullet類中創建一個靜態列表並將每個實例添加到它,這行得通嗎? 還是對於每個實施的項目符號都會改變?

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 */
}

這遵循繼承之上的合成原則,該原則使您可以保持代碼簡單並給予更多控制權:

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()方法內使用帶有所提供屬性的項目符號來使用此信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM