DEV Community

Erwan Le Tutour
Erwan Le Tutour

Posted on

Composite design pattern — Java

design-pattern

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
==============================

Top comments (2)

Collapse
 
j143 profile image
Janardhan Pulivarthi

Thanks. straightforward.

Collapse
 
erwanlt profile image
Erwan Le Tutour

thank you for your reading time, happy that this tutorial was able to help.