Composite design pattern — get the gist in 2 min.

aditya chaudhari
JavaDeveloperDiary — JDD
2 min readApr 11, 2023
composite design pattern UML

It’s about composing different objects of a similar family (interface) and then appearing them as one for an external client. Each object in the composition may or may not have child objects.

The Composite Design Pattern is a structural design pattern that allows you to compose objects into tree structures and then work with these structures as if they were individual objects.

Simple Example
Problem Statement

Suppose we are developing an e-commerce application where we have to implement the checkout process. The checkout process involves multiple steps such as adding items to the cart, applying discounts, selecting payment methods, and finally placing the order. Each of these steps can have different implementation details and can be subject to change in the future or can have specific conditions before execution. Our task is to design a flexible and extensible solution that can handle these changes and allow us to easily add new steps to the checkout process.
let’s try to use the composite design pattern for this requirment.

composite design pattern UML

please find [github code link] for code files.

As referred to in the above UML Component, leaf, composite, and client are important participants.
where,
component
in our case is CheckoutCompositeStep,
leaf’s are
CartProductsValidationStep, DiscountsStep, ShippingAddressStep, BillingAddressStep, PaymentStep and PlaceOrderStep.
composite is CheckoutCompositeStep which is responsible to define a hierarchy of checkout steps and treat the entire hierarchy as a single object

It may sound similar to the decorator pattern but intent of both the patterns is different, the composite pattern is used to represent part-whole hierarchies, while the decorator pattern is used to add functionality to an existing object without changing its structure. Both patterns can be useful in different situations, and it’s important to choose the right pattern for the job.

The real fun is in the details, if you wish to know and understand the pros-cons, and other important details please consider checking the detailed article at [composite-pattern-explained-5-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

On the journey to understand the core essence of design patterns.
Every week I publish a small 2 min post and a long 5–10 min post along with a code example, please consider following if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT