Full Stack • Java • System Design • Cloud • AI Engineering

Composite Design Pattern in Java

Learn Composite Design Pattern in Java with tree structures, file system examples, organization hierarchy, Spring examples, UML diagrams, code examples, benefits, limitations, and interview questions.

Introduction

Many enterprise applications deal with hierarchical structures.

Examples:

  • File Systems
  • Organization Hierarchies
  • Menu Systems
  • Banking Account Structures
  • Insurance Policy Groups
  • Product Categories

The challenge is:

Treat Individual Objects

and

Groups Of Objects

the same way.

This is solved using:

Composite Design Pattern


Purpose of Composite Pattern

The main purpose of Composite Pattern is:

Compose objects into tree structures
to represent part-whole hierarchies.

It allows clients to treat:

Single Object

and

Collection Of Objects

uniformly.


Real World Analogy

Think about a company organization.

CEO

 ├── Engineering Director
 │     ├── Team Lead
 │     ├── Developer
 │     └── Developer
 │
 └── HR Director
       ├── Recruiter
       └── Recruiter

Every node is an Employee.

Some employees manage others.

Some are individual contributors.

Yet we treat all as:

Employee

Composite Pattern Structure

flowchart TD

A[CEO]

A --> B[Engineering Director]

A --> C[HR Director]

B --> D[Team Lead]

D --> E[Developer 1]

D --> F[Developer 2]

C --> G[Recruiter 1]

C --> H[Recruiter 2]

Problem Without Composite

Without Composite:

Process Employee

Process Team

Process Department

Process Organization

Different logic is needed for each.

Code becomes complicated.


Solution With Composite

Treat everything as:

Organization Component

Whether it is:

Single Employee

or

Entire Department

Composite UML Structure

classDiagram

class OrganizationComponent {
    <<abstract>>
    +showDetails()
}

class Employee
class Department

OrganizationComponent <|-- Employee
OrganizationComponent <|-- Department

Department --> OrganizationComponent

Components

Component

Common interface.


Leaf

Individual object.

Example:

Developer
Recruiter
Manager

Composite

Container of components.

Example:

Department
Team
Organization

Step 1: Create Component

public interface OrganizationComponent {

    void showDetails();
}

Step 2: Create Leaf Class

public class Employee
        implements OrganizationComponent {

    private String name;

    public Employee(String name) {
        this.name = name;
    }

    @Override
    public void showDetails() {

        System.out.println(
            "Employee: " + name);
    }
}

Step 3: Create Composite Class

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

public class Department
        implements OrganizationComponent {

    private String name;

    private List<OrganizationComponent>
            components =
            new ArrayList<>();

    public Department(String name) {
        this.name = name;
    }

    public void add(
            OrganizationComponent component) {

        components.add(component);
    }

    @Override
    public void showDetails() {

        System.out.println(
            "Department: " + name);

        for (OrganizationComponent component
                : components) {

            component.showDetails();
        }
    }
}

Client Code

public class CompositeDemo {

    public static void main(String[] args) {

        Employee dev1 =
                new Employee("John");

        Employee dev2 =
                new Employee("Venu");

        Department engineering =
                new Department("Engineering");

        engineering.add(dev1);
        engineering.add(dev2);

        engineering.showDetails();
    }
}

Output

Department: Engineering

Employee: John

Employee: Venu

Object Flow

sequenceDiagram

participant Client

participant Department

participant Employee

Client->>Department: showDetails()

Department->>Employee: showDetails()

Employee-->>Department: Details

Department-->>Client: Complete

File System Example

The most famous Composite example.

File System:

Root

├── Documents
│    ├── Resume.pdf
│    ├── Notes.docx
│
├── Pictures
│    ├── Photo1.jpg
│    ├── Photo2.jpg

File System Diagram

flowchart TD

A[Root]

A --> B[Documents]

A --> C[Pictures]

B --> D[Resume.pdf]

B --> E[Notes.docx]

C --> F[Photo1.jpg]

C --> G[Photo2.jpg]

Banking Example

Bank Hierarchy:

Bank

├── Retail Banking

│    ├── Savings

│    ├── Current Accounts

│
├── Corporate Banking

│    ├── Loans

│    ├── Trade Finance

Banking Architecture

flowchart TD

A[Bank]

A --> B[Retail Banking]

A --> C[Corporate Banking]

B --> D[Savings]

B --> E[Current Accounts]

C --> F[Loans]

C --> G[Trade Finance]

Insurance Example

Insurance Product Tree:

Insurance

├── Health Insurance

├── Vehicle Insurance

├── Property Insurance

Composite allows uniform processing.


Menu Example

Website Navigation:

Home

Products
   ├── Laptops
   ├── Mobiles

Services
   ├── Support
   ├── Consulting

Menu Architecture

flowchart TD

A[Home]

A --> B[Products]

A --> C[Services]

B --> D[Laptops]

B --> E[Mobiles]

C --> F[Support]

C --> G[Consulting]

Microservices Example

Enterprise Service Hierarchy:

Customer Domain

 ├── Customer Service

 ├── Profile Service

 ├── Notification Service

 └── Preference Service

Composite can model domain ownership structures.


Spring Example

Category Entity

@Entity
public class Category {

    @Id
    private Long id;

    private String name;

    @ManyToOne
    private Category parent;

    @OneToMany(mappedBy = "parent")
    private List<Category> children;
}

This naturally forms a Composite structure.


E-Commerce Example

Product Categories

Electronics

 ├── Mobile

 ├── Laptop

 ├── Accessories

All categories are treated uniformly.


Composite Benefits

✅ Simplifies Tree Structures

✅ Uniform Processing

✅ Recursive Operations

✅ Flexible Hierarchies

✅ Easy To Extend

✅ Follows Open Closed Principle


Composite Limitations

❌ Recursive Processing Can Be Expensive

❌ Hard To Restrict Structure Rules

❌ Deep Trees May Impact Performance

❌ Debugging Large Hierarchies Can Be Difficult


When To Use

Use Composite when:

  • Tree Structures exist
  • Parent Child relationships exist
  • Groups and Individuals are treated the same

Examples:

  • File Systems
  • Menus
  • Organization Charts
  • Product Categories
  • Banking Structures

When Not To Use

Avoid Composite when:

  • No hierarchical relationship exists
  • Objects are completely independent
  • Tree traversal is unnecessary

Composite vs Decorator

Feature Composite Decorator
Purpose Tree Structure Add Behavior
Relationship Parent Child Wrapper
Focus Hierarchy Functionality

Composite vs Bridge

Feature Composite Bridge
Focus Tree Structure Separate Abstraction
Goal Part Whole Hierarchy Independent Evolution
Example File System Notification Providers

Framework Examples

Composite concepts appear in:

Framework Example
Spring Bean Hierarchies
Java Swing UI Components
JSF Component Trees
XML DOM Document Tree
HTML DOM Element Tree
JPA Parent Child Entities

Interview Questions

What is Composite Pattern?

A structural pattern that composes objects into tree structures and treats individual and composite objects uniformly.


What is a Leaf?

An individual object with no children.

Example:

Developer
File
Menu Item

What is a Composite?

An object containing other components.

Example:

Department
Folder
Menu

Real World Example?

File System hierarchy.


What problem does Composite solve?

It allows uniform processing of individual and grouped objects.


Where is Composite used in Java?

  • Swing Components
  • DOM Trees
  • Menu Structures
  • Category Hierarchies

Key Takeaways

  • Composite is a Structural Design Pattern.
  • It represents tree-like hierarchies.
  • Treats individual and composite objects uniformly.
  • Commonly used in file systems, menus, banking structures, and product catalogs.
  • Simplifies recursive processing of hierarchical data.
  • Widely used in enterprise applications and frameworks.