Java Structural Design Patterns – Composite Pattern

Composite Pattern is considered as a Structural Design Pattern. This pattern describes a group of objects and treating them as an individual instance of the same type of object because all exhibiting similar functionality.

In this pattern, we compose objects and creates a tree structure and represents part-whole hierarchies. Each node in the tree performs some task. In object-oriented programming, this is known as a “has-a” relationship between objects.

If you find that in your application code you are using multiple objects in the same way, and often have nearly identical code to handle each of them, then Composite Pattern is a good choice

The pattern defines below concepts-

  • Component – It is either an interface or an abstract class with the general methods to manage the child composites. It is the base interface.
  • Leaf – it represents leaf object in composite design, it has no children (no reference to the other objects.) and defines behavior for primitive objects in the composite pattern.
  • Composite – it stores children’s i.e leaf elements. It implements base component methods and defines child-related operations.
  • Client – it manipulates objects in the composition through the component interface.

Composite Pattern by Example

For understanding, we will take a simple example of company hierarchy. In this, we will have a General Manager, Manager, and Developer. If we refer above diagram, in our example we will try to create something like below 

Let us define the component-

The component interface is very simple and defines a print method.

We will define 2 composites as

and

Both the above composites are similar and they have a way to store their leaf nodes or you can say direct reportees.

Now let us add leaf component-

Running the example

The main program acts as a client and creates a hierarchy. If we run the example we will get below output.

The program prints Composite and their Children.

Conclusion

As mentioned earlier when clients need to ignore the difference between compositions of objects and individual objects you can use this pattern. Also, if programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then the composite pattern is a good choice. The source code is available in our Github repository.

Download Code

Add a Comment

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