tags:

views:

164

answers:

3

I'm preparing to build a 2D scene graph for my game, and i would like to know whether i should use at it's root an interface or two or a couple of abstract classes. Here's my requirements:

  • Base node item
    • needs to be able to store a matrix
    • also needs to be able to store a list of child nodes
    • as well as a single parent node
  • Transform node items
    • needs to have a Draw method (implementation is highly probable to be the same)
    • requires that the base node item be implemented/derived from
  • Drawable node item
    • needs to have a Draw method (implementation may be different)
    • requires that the base node item be implemented/derived from and cannot be implemented/derived from alongside the transform node item

What scheme of base classes/interfaces should i use for this?

+1  A: 

The differentiator would be if there's common code between all the classes that you can put into an abstract class and if they all need the same set of methods with this code. If this is the case, go with the abstract class. If there's no common code or you would end up making code common that shouldn't be common, then go with an interface.

jasonh
+2  A: 

Jasonh covered the basics -- use the abstract class where you want to share code, otherwise use the interface.

I wan to add one point -- even if you go the abstract class route, I'd still recommend creating an interface as well. You never know when you'll want to have a subclass that acts like the others, but really needs to inherit another class for some reason. Abstract base classes are great to save implementation code. Interfaces are more flexible though, so unless there's a really good reason (ie. your testing reveals you can't take the performance hit of virtual method calls), use an interface as well as an abstract base class where it makes sense.

My general rule on this is: use interfaces to define the API, and use abstract base classes to allow implementations of the interface to share code.

Jonathan
So if i understand you correctly, my best bet is to build some abstract classes that implement an interface so that i can still derive from other classes if need be?
RCIX
+2  A: 

Interfaces and abstract classes are used for two different things - interface are used for defining contract while abstract class are used to provide a base implementation and share common code. So you should definitly always use interfaces and sometimes (and I think your case is such a case) also abstract classes to avoid duplicating code.

So with interfaces only you will get the following.

class Transformation : INode, ITransformation { }
class GraphicsObject : INode, IGraphicsObject { }

I assume you can factor the common node specific code out into a base class.

abstarct class Node : INode { }

class Transformation : Node, ITransformation { }
class GraphicsObject : Node, IGraphicsObject { }
Daniel Brückner