I'm coding a little 2D game, all the game elements are subclasses of GameObject. The class Game has a collection of GameObject. My problem is, when the player performs an action, I go through the collection of GameObject to find what's in front of the player and then I want to use ONLY methods of interfaces implemented by the subclasses of GameObject without using instanceof and casting.
Here is a (very) simplified class-diagram of the situation
I tried to implement the visitor pattern but I want the function visit()
to take an Activable
or an Obstacle
as an argument and not a TV
or a Wall
.
Here a code example :
class Game {
private ArrayList<GameObject> gameObjects;
...
public void actionPerformed(...) {
GameObject current;
//find the focused Game object
...
//What's easiest but I don't want
if(gameObjects instanceOf Obstacle) {
((Obstacle) current).aMethod()
...
} else if (gameObjects instanceOf Activable) {
((Activable) current).activate()
...
}
...
//What visitor allow me
public void watchVisit(TV tv) {
tv.watch();
}
public void hitVisit(Wall w) {
//...
}
//What I want
public void activableVisit(Activable a) {
a.activate();
}
public void walkVisit(Obstacle o) {
//...
}
...
}
GameObject :
class GameObject {
public void acceptWatch(Game g) {
//Do nothing, only implemented in class TV
}
//Same with wall
...
}
TV :
class TV extends Item implements Activable {
public void acceptWatch(Game g) {
//this works if watchVisit take a "TV" but not if it's a "Activable"
g.watchVisit(this);
}
public void watch() {
...
}
...
}
How can I solve this problem?