Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:
See bookComposite
Structural patternThe Composite design pattern helps us constructing complex structures from simpler ones; in other words, we can use small structures to assemble a bigger and more complex structure.
The pattern's components are:
- Component: It usually is an interface or abstract class including the basic operations which will be used. This component should be extended by the other two components: Leaf and Composite.
- Leaf: It represents the smaller or simpler part of the entire structure, which inherits from Component. It's named after the tree theory, in which any node with no descendant receives such name. In this case, they are simple classes that haven't been built from others.
- Composite: This component is the one bringing life to this pattern, because it's built from a group of Components and Leafs. In tree theory, this component would represent a branch.
- El cliente realizar una acción sobre el CompositeA.
- CompositeA a su vez realiza una acción sobre CompositaB.
- CompositeB realiza una acción sobre LeafA y LeafB y el resultado es devuelto a CompositeA.
- CompositeA propaga la acción sobre LeafC, el cual le regresa un resultado.
- CompositeA obtiene un resultado final tras la evaluación de toda la estructura y el cliente obtiene un resultado.
Real-world example
By implementing the Composite design pattern, we are going to create an application that allows us to build a complex structure of products, where a product can either by just one single product or many products being represented as one. These groups of products, or composite products, can also be created by grouping many more composite products, all of them forming a tree structure where the price of a product comes from the sum of all its nodes prices being interpreted by the system as one single product.