Composite Design Pattern in Java: Comprehensive Guide

In this article, we will do an in-depth exploration of Composite Design Pattern in Java. So, let’s get started.

What is Composite Design Pattern in Java?

The Composite Design Pattern is a structural design pattern in Java that allows you to compose objects into tree structures to represent part-whole hierarchies. This pattern lets clients treat individual objects and compositions of objects uniformly.

In simpler terms, the Composite pattern allows you to create a structure of objects where each object can be treated individually or as a part of a larger structure. This is particularly useful when dealing with hierarchical structures, such as user interfaces, file systems, or organization hierarchies.

Key Components of the Composite Design Pattern:

  1. Component: This is an abstract class or interface that declares common methods for leaf nodes and composite nodes. It defines the interface for all objects in the composition.
  2. Leaf: This is the concrete implementation of the Component interface. It represents individual objects that do not have any children in the hierarchy.
  3. Composite: This is also a concrete implementation of the Component interface, but it represents a higher-level structure composed of one or more child components. It can contain other composite objects as well as leaf objects.

Example: Composite Design Pattern in Java

We would take up a simple example of an Employee.

An employee can be a CEO or a Vice President or can be a Trainee. CEO have VP as subordinates;VP have Delivery Managers as subordinates;Delivery Managers in turn have Project Managers as subordinates.Similarly, Project managers will have Trainees as subordinates. Trainees are at the bottom level and have no subordinates. Basically we create a Tree structure for the Employees.Our Employee class should be able to represent a CEO as well as it should be able to represent a Trainee.

In our example we will display the hierarchy of the Employees in an Organization.

Let us look into the Class Diagram and Java Code.

Class Diagram

Composite Design Pattern in Java

Java Code

package com.design.composite;

import java.util.ArrayList;
import java.util.List;

public class Employee {

    public Employee(String name, String designation) {
        this.name = name;
        this.designation = designation;
    }
    private List subOrdinates = new ArrayList < > ();
    private String name;
    private String designation;

    public void addSubOrdinate(Employee employee) {
        subOrdinates.add(employee);
    }
    public void removeSubOrdinate(Employee employee) {
        subOrdinates.remove(employee);
    }

    public void printHierarchy(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("\t");
        }
        System.out.print("[" + name + ", " + designation + "]");
        System.out.print("\n");
        for (Employee employee: subOrdinates) {
            employee.printHierarchy(depth + 1);
        }

    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRole() {
        return designation;
    }
    public void setRole(String role) {
        this.designation = role;
    }

}
package com.design.composite;

public class CompositeDemo {

    public static void main(String[] args) {
        Employee ceo = new Employee("Gyan", "CEO");
        Employee vp = new Employee("Prabhakar", "Vice President");
        Employee dm1 = new Employee("Rochit", "Delivery Manager");
        Employee dm2 = new Employee("Guru", "Delivery Manager");
        Employee manager = new Employee("Vivek", "Project Manager");
        Employee softwareTrainee = new Employee("Satya", "Trainee");
        manager.addSubOrdinate(softwareTrainee);
        dm1.addSubOrdinate(manager);
        vp.addSubOrdinate(dm1);
        vp.addSubOrdinate(dm2);
        ceo.addSubOrdinate(vp);
        ceo.printHierarchy(0);
    }

}

Output

Screen Shot 2016-08-21 at 6.04.08 pm

Use-Cases:Composite Design Pattern in Java

  1. User Interfaces: Building complex UI elements from simple controls (buttons, text fields).
  2. File Systems: Representing files and directories in a hierarchical structure.
  3. Organization Structures: Modeling departments, teams, and employees within an organization.
  4. Graphics and Drawing: Creating complex shapes from basic geometric elements.
  5. Menus and Hierarchies: Constructing nested menus or menu items.

Pros:Composite Design Pattern in Java

  1. Uniform Treatment: Clients can treat individual objects and compositions uniformly.
  2. Flexible Composition: Easily create complex structures from simple components.
  3. Encapsulated Structure: Hides the complexity of the underlying hierarchy.
  4. Recursive Composition: Supports nesting of composite and leaf objects.
  5. Open/Closed Principle: Adding new components doesn’t affect existing code.

Cons:Composite Design Pattern in Java

  1. Complexity: The pattern can lead to complex code and increased design effort.
  2. Performance Overhead: Recursive traversal might result in performance issues for large structures.
  3. Limited Type Safety: The Component interface might require methods not applicable to all subtypes.

Best Practices:Composite Design Pattern in Java

  1. Common Interface: Define a common Component interface for both leaf and composite objects.
  2. Clear Responsibilities: Make sure each class has clear responsibilities – leaf or composite behavior.
  3. Null Objects: Consider using Null Objects to handle missing components.
  4. Leaf Implementation: Leaf objects should implement methods directly, without composition logic.
  5. Composite Management: Composite objects should manage their child components.
  6. Safe Removal: Provide safe methods to add and remove components in composite objects.
  7. Caching Results: Cache expensive operations if they are expected to be called repeatedly.

Conclusion: Composite Design Pattern in Java

In this article, we delved into the Composite Design Pattern in Java, exploring its definition, components, example, and associated use-cases, pros, cons, and best practices. Let’s recap the main headings covered:

What is Composite Design Pattern in Java?

We defined the Composite Design Pattern as a structural design pattern that allows objects to be composed into tree structures, enabling uniform treatment of individual objects and compositions. This is particularly beneficial for hierarchical structures like user interfaces, file systems, and organization hierarchies.

Key Components of the Composite Design Pattern:

We introduced the core components:

  • Component: Abstract class or interface for common methods.
  • Leaf: Concrete implementation representing individual objects.
  • Composite: Concrete implementation representing higher-level structures.

Example: Composite Design Pattern in Java:

We explored a practical example involving an Employee hierarchy. This demonstrated how composite objects could be used to represent complex organizational structures.

Use-Cases: Composite Design Pattern in Java:

We highlighted scenarios where the Composite pattern proves useful, including user interfaces, file systems, organization structures, graphics, and menus.

Pros: Composite Design Pattern in Java:

We discussed the benefits, such as uniform treatment, flexible composition, encapsulated structure, recursive composition, and adherence to the Open/Closed Principle.

Cons: Composite Design Pattern in Java:

We outlined potential drawbacks, including increased complexity, performance overhead, and limited type safety.

Best Practices: Composite Design Pattern in Java:

We provided guidelines for implementing the pattern effectively, such as defining a common interface, maintaining clear responsibilities, handling missing components with Null Objects, and managing composition efficiently.

This comprehensive coverage equips you to comprehend, implement, and leverage the Composite Design Pattern in your Java applications, facilitating the creation of intricate yet manageable object hierarchies.

Must Read Design Pattern Articles: 

Leave a Reply

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