Subclassing classes with completely independent inheritance trees that cannot be modified
-
06-09-2019 - |
Question
How would someone join two classes each with independent inheritance trees to bridge context boundaries, given the restrictions that neither class's inheritance trees can be modified to inherit from the other?
i.e., if an item that is an entity saved to a database, let's say:
public class Stockitem : StockItemBase {
...
}
needs to be displayed using a drawing component, let's say:
Public class GraphicNode : BaseNode { ... }
It would be nice to simply have a subclassed stockitemgraphicnode
as there are many common members.
What is the best way to design a solution?
Solution
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
OTHER TIPS
With multiple inheritance it is possible, and if the trees are completely independent, you won't have the diamond problem.
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
).
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.