Composite

When ever we need to a tree structure, we use composite pattern.

Example - Simple Composite

There is a way to create really simple tree structure using composite patter (but we have to omit few classes in order to make it really simplistic).

class TreeNode {

    private String name;
    private List<TreeNode> children = new ArrayList<>();

    public TreeNode(String name) {
        this.name = name;
    }

    public void addChild(TreeNode child) {
        children.add(child);
    }

    public boolean isLeaf() {
        return children.size() == 0;
    }
}

Now we can create a tree using just TreeNode.

Example - Composite with an interface

Here is an example of composite pattern. Leaf can't have any children. Node can contain multiple implementations of Component interface. Node class is enabling the tree structure.

Here is how to create a tree using the classes above.

Complex example with simple algorithm

A mathematical formula can be represented as a tree. Lets try it out and see how composite works in real life.

Now we can construct mathematical formula. We are going to use this ((7+3)*(5−2)).

The program will print out the following.

Last updated

Was this helpful?