I'm working on a Java Android game. Games here generally need to use memory pools to avoid garbage collection.
For the sake of argument, say I have the following classes:
// Enemy in the game
class Enemy { int x; int y; abstract void update(); }
// Enemy that just bounces around
class Roamer extends Enemy { int direction; ... }
// Enemy that chases a player
class Chaser extends Enemy { Player target; ... }
// maybe 20 more enemy types...
Making use of subclasses is a pain when using memory pools as you need to e.g. say how many Roamer and Chaser objects you want upfront and not just how many Enemy objects you might need. Also, the virtual function calls to update can be slow.
One alternative I've thought of is to just merge all these classes into one e.g.
class Enemy
{
int direction;
Player target;
int type; // i.e. ROAMER_TYPE, CHASER_TYPE
}
I would then have an update function that checked the "type" variable and updated accordingly. This is obviously a more C-like approach. It feels hacky though because e.g. a roamer enemy will have a "target" variable it never uses. I'm unlikely to have more than a 100 enemies in memory at a time though so it really isn't a big deal memory wise. I just want some compromise between nice code and speed.
Does anyone have any comments on how best to structure this? Is merging classes like this going too far? Is this ever a good idea? Should I just use a regular class tree?
I know there are no right answers to this, but I'd like some different viewpoints.