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

时间:2014-12-01 03:29:09

标签: java nullpointerexception factory-pattern

我正在尝试实现工厂模式/方法来创建一个新类,但我一直得到一个空指针异常。我已经完成了代码,但我似乎无法弄清楚它是什么。

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);运行时,我得到一个空指针异常。任何想法为什么会这样?我觉得我错过了一些非常明显的东西。

2 个答案:

答案 0 :(得分:0)

因为您从未初始化enemyList

你需要一个enemyList = new ArrayList<Enemy>

附加说明:将int变量用作magic numbers并不是一个好主意。使用自定义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;
  ...
}

答案 1 :(得分:0)

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