Composite Design Pattern in Java

The composite pattern is a structural design pattern. This pattern is also called a partitioning pattern. This pattern explains that a group of objects will be treated as a same way as a single instance of an object. The intention of the composite pattern is to compose objects into tree hierarchies to represent the part-whole relationship.

In composite pattern, the tree structure exists where identical operations can be performed on leaves and nodes. A node in a tree is a class that can have children. A leaf in a tree does not have children. The children of a composite can be leaves or other composites.

The main benefit of composite pattern is it defines class hierarchies consisting of primitive and composite objects. It also makes provision for us to add new kind of components.

Usage

When clients use to ignore the difference between composition of objects and individual objects.
When the structure can have any level of complexity and is dynamic.

Class Diagram

Composite Pattern in Java
Implementation

Let’s take an example of the composite design pattern. First, we will declare a Greeting interface that declares operations that are common for the composite class and the leaf class. This allows us to perform operations on composites and leaves using one standard interface.

The Leaf class has a name field and implements the sayWelcome() and sayGoodbye() methods of the Greeting interface by displaying messages to the standard output.

The Composite class implements the Greeting interface. It implements sayWelcome() and sayGoodbye() methods by calling these same methods on all of its children, which are Greetings (since they can be both Leaf objects and Composite objects, which both implement the Greeting interface).

The CompositePatternTest class demonstrates the composite design pattern.

Run the above class. You will find below output in the console.

Output 

From the above output, we can see that the composite pattern allows us to perform operations on the composites and leaves that make up a tree structure via a common interface.

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.