The best template for structuring and implementing an aggregate (or similar) method in node tree data

I had a problem while implementing aggregated (or similar) methods in the data hierarchy of the node tree. As you can see, generics are a little spoiled here, which is unsatisfactory for me, so my question is: is there a better way to implement it (perhaps avoiding casting down the hierarchy from the object into aggregated methods)?

Current situation (devoid of unrelated details):

public interface AggregableTreeData<T extends AggregableTreeData> { void aggregate(T from); } public abstract class FruitTreeData<T extends FruitTreeData<?>> implements AggregableTreeData<T> { private BigDecimal size = BigDecimal.ZERO; @Override public void aggregate(T from) { this.size = this.size.add(from.size); } } public class OrangeTreeData<T extends OrangeTreeData<?>> extends FruitTreeData<T> { private boolean ripened = false; @Override public void aggregate(T from) { this.ripened = this.ripened || from.ripened; } } 

In addition, I have a method that aggregates tree data that looks like this:

 //child.getData() and node.getData() is of type <T extends AggregableTreeData<T>> void aggregateNode(TreeNode node) { for (TreeNode child : node.getChildren()) { aggregateNode(child); node.getData().aggregate(child.getData()); } } 
+4
source share
1 answer

It looks very similar to the task for a composite template.

+1
source

All Articles