如何通过从变量中提取类型来创建对象?

时间:2013-07-16 00:50:20

标签: java class types

我一直在使用Java级别阅读器,从我的游戏的XML文档中提取级别数据。一切都很顺利,但我遇到了一个问题。我从文档中提取的一件事是要创建的游戏对象的ID。我有一堆类,如墙,玩家和硬币,所有这些类都扩展了GameObject类。我想在GameObject类中有一个方法,它根据ID返回一个GameObject。像这样:

public GameObject CreateGameObject(int id, int x, int y, GameScreen parent) {
    Type type = getTypeFromList(id);
    Type gobj = new Type(x,y,parent);
    return gobj;
}

我知道我可以使用一堆if语句来检查ID并返回正确的ID,但我希望代码干净且更通用。如果你能帮我告诉我如何做到这一点或给我看另一种非常感激的方式。

1 个答案:

答案 0 :(得分:1)

我建议使用工厂界面进行GameObject创建,并为每种类型实施一个实现(如arynaq mentioned in the comments):

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也可以发挥作用:

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);
    }
}