Design Patterns, Recursion – Does the Composite Design Pattern Implement Recursive Behavior?

design-patternsrecursion

The Composite design pattern allows us to call an operation() on a 'composite' node in a tree structure, and this operation() will be called on all of the children, subchildren and so on.

When an element's operation() is invoked, it is it's responsibility to call operation() on all of it's children, and so on. Each child responsible to invoke the operation on it's own direct children.

I understand why this has a recursive nature. When we learn of this design, the word 'recursion' is inside our heads all the time.

But can this be considered 'recursive behavior' in the strict sense of the word?

I always thought that recursion simply means a process where 'a function calls itself'. ('function' or 'method' or 'procedure' etc).

However, in the Composite design pattern, no method calls itself. A method calls the identically-named method in the objects composed with it (serving as it's 'children') – but it never calls itself (aka void operation(){ this.operation(); } never happens).

So, does the Composite design pattern create recursive behavior? Or does it create behavior resembling the nature of recursion? Is my definition of recursion wrong because it's too strict? If so, how would you define recursion?

Best Answer

Composite creates Recursive Data Type which then needs recursive functions or operations to fully traverse. In a sense Composite creates tree-like structure.

Then yes, Composite has recursive behavior.

Related Topic