First of all, I apologize for “yet another interface question”. I thought that this one might be worth asking, though, as it’s kind of a strange issue. The project I’m using uses Actionscript 3, but this is more of a general OOP question.
Here’s the situation:
I have a class that already inherits from a base class; it’s an object in a videogame. (Let’s say it’s a spaceship.) In my game, I’d like to have many many many spaceships onscreen, at one time, so I’ve decided to create an object pool using a linked-list structure.
Logically, because class Spaceship already inherits from a base class, I would use an interface to define methods pertaining to a linked list. Doing this, additionally, would allow me to extend these methods to other classes – class Asteroid, or class Bullet, or class Particle, for instance.
Here’s the problem – the strength of an interface is that it lets you redefine the implementation for every class you use, based on what you need. For something like a linked list, though, the code isn’t going to change between classes. Since I plan on having a lot of classes that will implement these object pool methods, I’d really like to avoid reusing the same implementation code over and over within each new class.
Question: Is there a way to avoid reusing the same exact linked list code for each class I use? Or is this just an inevitability? It seems like this violates the Once and Only Once principle. Is it possible to define a full function within an inheritance block, instead of just its prototype?
If this is a stupid question, let me know. (If I’m asking whether it is, it probably is, but hey, can’t learn without being stupid once in a while.) It just seems that there should be a more logical way to do something like this.
In other languages, that support multiple inheritance, there is an easy way to do it without all your game objects needing to have a common ancestor: your spaceships could inherit from a base ship class, as well as a linked list element class. Unfortunately, AS3 does not support multiple inheritance, so you have to choose to either:
A. Use an interface exactly as you suggest
or
B. Have all your game object base classes inherit from a common ancestor that implements the linked list functionality and extends Sprite (or MovieClip), instead of your game object base classes extending Sprite or MovieClip directly.
I’d probably go with the latter, to solve your exact problem. I’d probably derive from Sprite or MovieClip and call the thing GamePoolObject or something to that effect…