lundi 11 décembre 2017

Giving objects the ability to recreate

I'm putting together a game in Java. Basically, you need to avoid oncoming game objects. I want to recreate these objects once they have left the screen.

I'm trying to adhere to design patterns, I currently have a GameObject Factory that is responsible for creating the game worlds' objects. All of these objects are derived from an abstract GameObject. I was considering creating a Recreatable interface that exposed a recreate method, that recreate method then expects a GameObject Factory which in turn returns another random version of that game object.

Like this

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

}

I could then just check if it's an instance of re-creatable and if so add that recreated object to my list of moving game objects instead of doing a switch case/if else block of all the possible game objects.

Is this a bad way of going about it?

Aucun commentaire:

Enregistrer un commentaire