OOP Design Patterns— Composite Pattern
When there is a hierarchical structure, there are 2 types of components Leaf nodes and Composite nodes. Usually in this type of scenario, we will have to check which type the component is before performing some action on them using an if-else block.
The composite pattern provides us a way to treat Leaf nodes and Composite nodes uniformly, then performing a computation on any node becomes trivial and the code becomes cleaner. We are trying to replace conditionals with polymorphism
We can put them in a Data structure and ignore the differences between compositions of objects and individual objects.
Definition: The composite pattern allows to compose objects into tree-like structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly
This sounds similar to decorator pattern but it is mostly to do with the intent why we are doing this.
- Decorator Pattern — Attaches additional responsibilities dynamically(in runtime) without opening up. supporting open-closed principle
- Composite Pattern — Used when data is hierarchical by nature — replace conditionals with polymorphism