Suppose I have the following interfaces, GameObject
and Enhance
.
GameObject:
public interface GameObject {
void prepare();
void use();
void cleanup();
}
Enhance:
public interface Enhance {
int increase();
int decrease();
}
Goggles:
public abstract class Goggles implements GameObject, Enhance {
// The actual implementation is unnecessary to my question.
// Just note that the class implements GameObject and Enhance.
}
HealthPack:
public abstract class HealthPack implements GameObject {
// The actual implementation is unnecessary to my question.
// Just note that the class implements GameObject.
}
Character:
public abstract class Character {
private final List<GameObject> inventory;
private final List<Goggles> goggles;
private final List<HealthPack> health;
public Character() {
this.inventory = new ArrayList<GameObject>();
this.goggles = new ArrayList<Goggles>();
this.health = new ArrayList<HealthPack>();
}
public void viewInventory(){
this.drawGrid(this.inventory);
this.drawGrid(this.goggles); // -- BOOM!
}
private void drawGrid(List<GameObject> items){
}
}
As you probably notice, I can't pass List<Goggles> goggles;
and List<HealthPack> health;
to the drawGrid(List<GameObject> items)
method.
I could have a private draw method for each specific abstract type,
private void drawGoggles(List<Goggles> goggles)
private void drawHealthPack(List<HealthPack> healthPack)
but this means that for every new abstract type, I need a new draw method.
Maybe Grid
itself is a class and an instance of grid can be given to each GameObject
which will then pass an image and number of squares it takes up on the Grid
. This way, it doesn't matter what specific type the GameObject
is, the Grid class will only receive an Image
object.
In general, what is the cleanest way to restructure the code?