繁体   English   中英

使用工厂方法获取空指针异常

[英]Getting Null Pointer Exception with Factory Method

我正在尝试实现Factory Pattern / Method来创建一个新类,但是我不断收到Null Pointer异常。 我已经逐步完成了代码,但似乎无法弄清楚它是什么。

public class RandomEnemy {

SpaceShipFactory theFactory;
private ArrayList<SpaceShip> enemyList;

public RandomEnemy(){
    setFactory(new SpaceShipFactory());
}

public void createRandomEnemy(int i){
    SpaceShip s;
    s = this.theFactory.createShip(i);
    enemyList.add(s);
}


public void setFactory(SpaceShipFactory theFactory){
    this.theFactory = theFactory;
}


}

和工厂类:

public class SpaceShipFactory {

public SpaceShip createShip(int i){
    SpaceShip s = null;


    if(i == 1){
        s = new SpaceShip(QuickLoad("battlecruiser"), 0, 0, 256, 256);
        System.out.println("Result is battlecruiser");
    }
    else if(i == 2){
        s = new SpaceShip(QuickLoad("battleshooter"), 0, 0, 256, 256);
        System.out.println("Result is battleshooter");
    }
    else if(i == 3){
        s = new SpaceShip(QuickLoad("battlestar"), 0, 0, 256, 256);
        System.out.println("Result is battlestar");
    }


    return s;
}
}

enemyList.add(s); 运行时,我得到一个空指针异常。 任何想法为什么会这样? 我觉得我缺少明显的东西。

因为您永远不会初始化enemyList

您需要在某个地方enemyList = new ArrayList<Enemy>

补充说明:将int变量用作幻数不是一个好主意。 使用一个自定义的enum (它可能还包含许多特定于船舶的数据,以免根本没有工厂),例如:

enum ShipType
{
  BATTLE_STAR("battlestar"),
  BATTLE_CRUISER(battlecruiser"),
  BATTLE_SHOOTER("battleshooter",

  public final String name;

  private ShipType(String name) { this.name = name; }
}

class SpaceShip
{
  ShipType type;
  ...
}

首先敌人列表没有初始化。 如果i值不在{1,2,3}之间,则返回的是s,它是SpaceShip的引用变量,并且未实例化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM