我建议使用工厂接口进行GameObject
创建,每种类型都有一个实现(如评论中提到的 arynaq):
interface GameObjectFactory {
GameObject create(); // this could also take arguments like x, y, and parent
}
private static final Map<Integer, GameObjectFactory> FACTORIES_BY_ID;
static {
final Map<Integer, GameObjectFactory> factoriesById = new HashMap<>();
// ID 42 is for walls
factoriesById.put(42, new GameObjectFactory() {
@Override
public GameObject create() {
return new Wall();
}
});
//etc.
FACTORIES_BY_ID = factoriesById;
}
如果 ID 是连续的,您也可以使用数组:
private static final GameObjectFactory[] FACTORIES = {
// ID 0 is for walls
new GameObjectFactory() {
@Override
public GameObject create() {
return new Wall();
}
}
};
枚举也可以工作:
enum GameObjectFactory {
WALL(42) {
@Override
GameObject create() {
return new Wall();
}
};
private final int id;
private GameObjectFactory(int id) {
this.id = id;
}
abstract GameObject create();
static GameObjectFactory getById(int id) {
for (GameObjectFactory factory : values()) {
if (factory.id == id) {
return factory;
}
}
throw IllegalArgumentException("Invalid ID: " + id);
}
}