Search code examples
design-patternscomposite

Composite design pattern - strategy for tracking leafs in the tree structure


What is a good strategy for tracking leafs in a tree structure?

For my purposes, my leafs are given names but the names don't mean much without knowing where they exist within the tree. For example, there may be numerous leafs of the same name so I'll need to know which "branch" they reside on.

Any recommended techniques?


Solution

  • Composite Pattern lets you treat your leaves and their parents\branches the same way while traversing. Also, it gives you the facility to change the logic of the 'main functional' method to iterate over the children for an aggregate component (or branch in your case) and just do something for a leaf component.

    Now coming back to the problem which you have regarding leaf having to know about the branch which they belong to - I presume that the leaves in your solution must have a reference back to their parent/branches. Then when you traverse the tree for leaves you are allowed to bring out the parent information along with the leaf information. This should solve the problem if you want to know about the parent branches. In case you want to keep information for up to 2-levels(grandparents) or more levels up then you can build a recursive method which traverses upwards until some ancestor condition is met or the tree's root is reached.

    To summarize my point - Composite Pattern's handling is related to handling the trees and branches in a generic way. But what logic is to be executed on encountering each of them can vary based on the type of node. This gives the flexibility to have logic specific to the node-type which I gave an example of in the above paragraph. What's in that logic - Composite Pattern is not concerned with it as long as the base type of all the nodes is same and traversal goes along smoothly.

    I hope it helps solve your problem. I have written an article in my blog on Composite Design Pattern - http://www.javabrahman.com/design-patterns/composite-design-pattern-in-java/ . You can refer to it to get more understanding on this pattern - if required.