Composite Design Pattern Implementation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

This article will continue with series of structural design patterns and concentrate on composite design pattern implementation.

Composite Design Pattern Implementation:

Composite pattern allows you to compose objects into tree structure to represent part whole hierarchies. It lets clients treat individual objects and compositions of those objects uniformly.

In simpler words, we can call same methods on individual objects as well as composite objects which are made up of individual objects. Individual objects are leaf nodes of tree structure while composite objects are treated as branches of tree. Composite objects will have individual objects as their leaf nodes. Performing any operation on composite objects will yield similar results as that of operations performed on individual objects.

Generic Class Diagram:

Composite Pattern

Composite Pattern

Participants involved are:

  • Component: This represents individual objects as well as composite object.
  • Leaf: Leaf implements Component and acts as leaf node. i.e. it is not composed of many objects.
  • Composite: implements Component and acts as a combination of individual objects.
  • Client: Interacts with other entities in pattern.

Composite Design Pattern Implementation Example:

Consider we want to build a car with specific parts. Each part has its own existence and it can be added to a car. We want to perform some operation on car and want it to be done on all its individual objects.

  • Create a Component interface with printDetails() method in it.
  • Create a class Part which implements Component. This acts as leaf node and individual object.
  • Create a class Car which implements Component, This acts as composite object. It holds a list of individual elements and a way to add them into existing list.

Component.java:

Part.java

Car.java:

Note that we have written addPart(Component part) method which adds a part in existing parts. Now it is time to test it out.

Dealer.java:

Output:

Example Class Diagram:

Composite Pattern Example

Composite Pattern Example

I hope this helped understand composite design pattern implementation.

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *