I have a tree-like structure as shown in below picture (as one small example). The tree consists of two different node types, that are:
- Data Nodes: These nodes that are colored in yellow contain about ten attributes. They always appear in the leaves of the tree.
- Collection Nodes: That are shown in blue. They are sharing
Id
andType
attributes with theData Nodes
and also keep an ordered list of their children.
This tree is created in one component and sent to another system for manipulation (Saving, showing in GUI, etc.). To design this tree, there are different approaches that I have described below with their advantages and disadvantages. What do you think about them and which one is the most appropriate one in this case?
Approach 1:
Have a interface for common functionalities (e.g. getId
, getType
) and put the specific functionalities (e.g. getChildren
) in concrete classes. This way, the other application that needs to manipulate the tree (for saving or showing in GUI), needs lots of down-casing based on the type of the node.
Approach 2: Have one interface for all of the functionalities of both node types. In each concrete class, either implement the method (if applicable) or throw an exception. It is the responsibility of the user to call the right method based on the type of the node.
Approach 3:
Do not go for an interface. But just have one class (e.g. TreeNode
) with the all data + methods of both node types. It is again the responsibility of the user to call the right method on the right object type.
p.s. The implementation language will be C++11, if it matters.
Update 1: More information about this tree and more specific requirements are described below:
- The tree is created in a source system using a provided API. In this context, the user creates the tree hierarchy and sets the value of each node.
- The second system that uses this tree, is responsible for saving/loading the tree and also its display in a GUI. These actions usually need walking over ALL nodes of the tree. In addition, this second system can edit the tree elements using the GUI or do a search on the tree for some values.