Composite pattern is one of the Structural design pattern. Composite design pattern is used when we have to represent a part-whole hierarchy.

Composite Design Pattern

When we need to create a structure in a way that the objects in the structure has to be treated the same way, we can apply composite design pattern.

Lets understand it with a real life example – A diagram is a structure that consists of Objects such as Circle, Lines, Triangle etc. When we fill the drawing with color (say Red), the same color also gets applied to the Objects in the drawing. Here drawing is made up of different parts and they all have same operations.

Composite Pattern consists of following objects.

  1. Base Component – Base component is the interface for all objects in the composition, client program uses base component to work with the objects in the composition. It can be an interface or an abstract class with some methods common to all the objects.
  2. Leaf – Defines the behaviour for the elements in the composition. It is the building block for the composition and implements base component. It doesn’t have references to other Components.
  3. Composite – It consists of leaf elements and implements the operations in base component.

Here I am applying composite design pattern for the drawing scenario.

Composite Pattern Base Component

Composite pattern base component defines the common methods for leaf and composites. We can create a class Shape with a method draw(String fillColor) to draw the shape with given color.

Shape.java

Composite Design Pattern Leaf Objects

Composite design pattern leaf implements base component and these are the building block for the composite. We can create multiple leaf objects such as Triangle, Circle etc.

Triangle.java

Circle.java

Composite object

A composite object contains group of leaf objects and we should provide some helper methods to add or delete leafs from the group. We can also provide a method to remove all the elements from the group.

Drawing.java

Notice that composite also implements component and behaves similar to leaf except that it can contain group of leaf elements.

Composite-Pattern-java

Our composite pattern implementation is ready and we can test it with a client program.

Composite Design Pattern Client Program

TestCompositePattern.java

Output of the above composite pattern client program is:

Composite Pattern Important Points

  • Composite pattern should be applied only when the group of objects should behave as the single object.
  • Composite design pattern can be used to create a tree like structure.

java.awt.Container#add(Component) is a great example of Composite pattern in java and used a lot in Swing.

Earlier structural design pattern articles:

By admin

Leave a Reply

%d bloggers like this: