views:

71

answers:

4

How would someone join two classes each with independant inheritance trees to bridge context boundaries, given the restrictions that nether class's inheritance trees can be modified to inherit from the other

ie

if a item that is an entity saved to a database lets say

public class Stockitem : StockItemBase { ... }

needs to be displayed using a drawing component lets say Public class GraphicNode : BaseNode { ... }

It would be nice to simply have a subclassed stockitemgraphicnode as there are many common members

My question is what is the best way to design a solution?

A: 

With multiple inheritance it is possible, and if the trees are completely independent, you won't have the diamond problem.

vartec
A: 

You may have an instance of GraphicNode object inside the StockItem.

This named Composition: http://en.wikipedia.org/wiki/Object_composition

Then create methods in StockItem that would simply delegate real work to the enclosed GraphicNode.

amartynov
+2  A: 

Composition.

Create a new class that inherits from neither but has an instance of both the classes you want to use within it, then expose the methods you want to call.

Google "Composition over Inheritence" for much better ramblings on the subject than mine

MrWiggles
A: 

Multiple inheritance can be used if the language allows it. I don't know much about it however.

Otherwise, you can build a StockItemNode : GraphicNode from a StockItem:

class ItemNodeFactory
{
  ...
  StockItemNode create(StockItem);
  ...
}

You can transfer properties from StockItem into an instance of StockItemNode (set-get) which would completely decouple the two types. Or you can have StockItemNode wrap an instance of StockItem (composition).

Doing it the other way around (having NodeStockItem : StockItem and/or wrapping a GraphicNode in a StockItem) would result in a particular bad design because you don't want to hardwire a coupling to a specific presentation (GraphicNode) inside a domain/business/data entity (StockItem).

eljenso