How to refactor my design, if it seems to require multiple inheritance?
- by Omega
Recently I made a question about Java classes implementing methods from two sources (kinda like multiple inheritance). However, it was pointed out that this sort of need may be a sign of a design flaw. Hence, it is probably better to address my current design rather than trying to simulate multiple inheritance.
Before tackling the actual problem, some background info about a particular mechanic in this framework:
It is a simple game development framework. Several components allocate some memory (like pixel data), and it is necessary to get rid of it as soon as you don't need it. Sprites are an example of this.
Anyway, I decided to implement something ala Manual-Reference-Counting from Objective-C. Certain classes, like Sprites, contain an internal counter, which is increased when you call retain(), and decreased on release().
Thus the Resource abstract class was created. Any subclass of this will obtain the retain() and release() implementations for free. When its count hits 0 (nobody is using this class), it will call the destroy() method. The subclass needs only to implement destroy().
This is because I don't want to rely on the Garbage Collector to get rid of unused pixel data.
Game objects are all subclasses of the Node class - which is the main construction block, as it provides info such as position, size, rotation, etc.
See, two classes are used often in my game. Sprites and Labels.
Ah... but wait. Sprites contain pixel data, remember? And as such, they need to extend Resource.
But this, of course, can't be done. Sprites ARE nodes, hence they must subclass Node. But heck, they are resources too.
Why not making Resource an interface?
Because I'd have to re-implement retain() and release(). I am avoiding this in virtue of not writing the same code over and over (remember that there are multiple classes that need this memory-management system).
Why not composition?
Because I'd still have to implement methods in Sprite (and similar classes) that essentially call the methods of Resource. I'd still be writing the same code over and over!
What is your advice in this situation, then?