Composite design pattern — Java
Erwan Le Tutour
Posted on January 28, 2022
Definition of Composite pattern
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
Where to use the Composite pattern?
When we want to implement the same interface on leaves and composites so that they are handled in the same way.
UML example
Implementation of the Composite pattern
First we need to declare the interface that will describe the behavior of our component.
Then the implementation will have the same behavior but with some hierarchy between them.
The only difference in these implementations are the use of the addParent() and addChild() to create the hierarchy like we can see the following example and the output it will produce.
==============================
Name : Philippe
Last name : Le Tutour
Childs :
- Name : Erwan
==============================
==============================
Name : Erwan
Last name : Le Tutour
Parents :
- Name : Philippe
Childs :
- Name : Mathys
==============================
==============================
Name : Mathys
Last name : Le Tutour
Parents :
- Name : Erwan
- Name : Amelie
==============================
💖 💪 🙅 🚩
Erwan Le Tutour
Posted on January 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.