I got a big infrastructure with lots of nested classes and i’m looking for the right design pattern.
I will explain:
I got a class called “Title” and class called Item
A Title contain different items , each item contain different data
You can see in the schematic the Title contain also ItemList which contains more items.
each item can contain item.
I’m adding a schematic of the infrastructure , It looks like a non binary tree
I’m looking for the best data structure for this object,
Requirements:
- With Node id and Tree Node i will be able to find the Node in a fast way
- Good code maintainability
- Can switch from flat to tree and from tree to flat
Your question seems to request a quick way to access nodes given their ID value regardless of the hierarchy. In this case you would probably be best off (as Daniel Gabriel suggests in the comments) to create a flat list optimized for “searching” the flat list of IDs, since your look-up operation doesn’t care about the hierarchy. Just because you have your objects in a tree structure doesn’t mean you can’t also index them in another structure. A dictionary should be very good at this – the key could be an integer (or whatever your node id is) and the value could refer to the node object instance. You just have to remember to keep this structure in sync with your tree structure. Remove keys from the dictionary when nodes are removed, and add them to the dictionary when nodes are added (if the structure is dynamic).
This fulfills your requirement #1, and probably #2 (if you encapsulate the synchronization of the index in the same class if necessary). For #3 we may need more information, but if you keep these structures synchronized, you will always have access to both formats without a need for conversion. Should be very easy.
Here is some sample code that demonstrates how to encapsulate a structure that can provide both flat index and tree structures at all times: