使对象能够重新创建

时间:2017-12-11 21:42:44

标签: java android oop design-patterns

我正在用Java编写游戏。基本上,你需要避免迎面而来的游戏对象。我想在离开屏幕后重新创建这些对象。

我正在努力坚持设计模式,我目前有一个GameObject Factory负责创建游戏世界的对象。所有这些对象都是从抽象的GameObject派生的。我正在考虑创建一个Recreatable接口,它暴露了一个重新创建的方法,重新创建方法然后需要一个GameObject Factory,然后又返回该游戏对象的另一个随机版本。

喜欢这个

public class Ghost extends GameObject implements Recreatable, Movable {

    private int x;
    private int y;
    private int dx;
    private int dy;

    public Ghost(int x, int y) {
        this.x = x;
        this.y = y;
        dx = 3;
        dy = 5;
    }

    public void move() {
        // move logic ...
    }

    public GameObject recreate(GameObjectFactory gameObjectFactory) {
        return gameObjectFactory.getInstance("ghost");
    }
}

然后我可以检查它是否是一个可重新创建的实例,如果是这样的话,将重新创建的对象添加到我的移动游戏对象列表中,而不是做一个切换案例/ if else阻止所有可能的游戏对象。

这是使用重新创建方法

的外观示例
public class GameSurfaceView extends SurfaceView implements Runnable {

    private ArrayList<Movable> movables;
    private GameObjectFactory gameObjectFactory;

    public GameSurfaceView(Context context) {
        super(context);
        gameObjectFactory = new GameObjectFactory(this);
    }

    @Override
    public void run() {
        while (isRunning) {
            if (!myHolder.getSurface().isValid())
                continue;

            ListIterator<Movable> movableListIterator = movables.listIterator();

            while (movableListIterator.hasNext()) {
                Movable movable = movableListIterator.next();

                movable.move(canvas);

                if (movable.hasPassedScreen()) {
                    if (movable instanceof Recreatable) {
                        Recreatable recreatable = (Recreatable) movable;
                        movableListIterator.set(recreatable.recreate(gameObjectFactory));
                    }
                }
            }
            myHolder.unlockCanvasAndPost(canvas);
        }
    }
}

对于run方法,if / else看起来更像是

        while (movableListIterator.hasNext()) {
        Movable movable = movableListIterator.next();

        movable.move(canvas);

        if (movable.hasPassedScreen()) {
            if (movable instanceof GhostObject) {
                movableListIterator.set(gameObjectFactory.getInstance("ghost"));
            } else if (movable instanceof WitchObject) {
                movableListIterator.set(gameObjectFactory.getInstance("witch"));
            } else if (movable instanceof VampireObject) {
                movableListIterator.set(gameObjectFactory.getInstance("vampire"));
            } else if (movable instanceof ZombieObject) {
                movableListIterator.set(gameObjectFactory.getInstance("zombie"));
            }
        }

    }

这是一个不好的方式吗?

0 个答案:

没有答案