DEV Community

DevCorner2
DevCorner2

Posted on

🌳 Composite Design Pattern β€” Java LLD + UML + Real Use Cases

Compose objects into tree-like structures to represent part-whole hierarchies.
Treat individual objects and compositions uniformly.


🧠 What Is the Composite Pattern?

The Composite Pattern is a structural design pattern that:

  • Allows you to treat individual objects and groups of objects the same way.
  • Commonly used to build tree structures (e.g., filesystems, UIs, org charts).
  • Enables recursive structures using "has-a" relationships.

βœ… Real-World Use Cases

Use Case Description
πŸ“‚ File System Files and directories, both implement Node
πŸ§‘β€πŸ’Ό Org Chart Employees and managers all implement Employee
🧱 UI Component Hierarchy Buttons, Panels, Containers implement Component
🧾 HTML/XML Elements Tags nested inside other tags
πŸ§ͺ Test Suites Individual tests and test groups run recursively

🎯 Key Idea

Let clients treat leaf nodes and composite nodes uniformly via a shared interface.


πŸ“ UML Diagram

            +---------------------+
            |     Component       |  <<interface>>
            +---------------------+
            | +operation()        |
            +---------------------+
                    β–²
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β–Ό                             β–Ό
+-------------+           +----------------+
|   Leaf      |           |   Composite    |
+-------------+           +----------------+
| +operation()|           | - children[]   |
|             |           | +add(Component)|
+-------------+           | +remove(Component)|
                          | +operation()   |
                          +----------------+
Enter fullscreen mode Exit fullscreen mode

πŸ’» Java Example β€” File System

We’ll design a virtual file system where:

  • File is a Leaf
  • Directory is a Composite
  • Both implement FileSystemNode interface

βœ… FileSystemNode.java (Component)

public interface FileSystemNode {
    void show(String indent);
}
Enter fullscreen mode Exit fullscreen mode

βœ… File.java (Leaf)

public class File implements FileSystemNode {
    private final String name;

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

    @Override
    public void show(String indent) {
        System.out.println(indent + "πŸ“„ " + name);
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Directory.java (Composite)

public class Directory implements FileSystemNode {
    private final String name;
    private final List<FileSystemNode> children = new ArrayList<>();

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

    public void add(FileSystemNode node) {
        children.add(node);
    }

    public void remove(FileSystemNode node) {
        children.remove(node);
    }

    @Override
    public void show(String indent) {
        System.out.println(indent + "πŸ“ " + name);
        for (FileSystemNode child : children) {
            child.show(indent + "  ");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Client.java

public class CompositePatternDemo {
    public static void main(String[] args) {
        Directory root = new Directory("root");
        File file1 = new File("resume.pdf");
        File file2 = new File("notes.txt");

        Directory photos = new Directory("Photos");
        File img1 = new File("pic1.jpg");
        File img2 = new File("pic2.png");

        photos.add(img1);
        photos.add(img2);

        root.add(file1);
        root.add(file2);
        root.add(photos);

        root.show("");
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Output

πŸ“ root
  πŸ“„ resume.pdf
  πŸ“„ notes.txt
  πŸ“ Photos
    πŸ“„ pic1.jpg
    πŸ“„ pic2.png
Enter fullscreen mode Exit fullscreen mode

✨ Benefits

Benefit Description
βœ… Uniformity Treat leaf and composite objects the same
βœ… Recursive composition Build flexible, nested structures
βœ… Open/Closed Principle Add new types of nodes without affecting others
βœ… Hierarchical navigation Natural for tree-based data models

⚠️ Limitations

  • ❌ Can make code harder to understand if overused
  • 🧩 Composite structure can be too generic β€” use only where hierarchy is meaningful
  • Requires careful traversal to avoid performance hits on large trees

🧾 Summary

Aspect Details
Pattern Type Structural
Used For Tree-like hierarchy modeling
Design Principle Treat part and whole uniformly
Java Examples java.awt.Component, javax.swing.JComponent
Ideal For File system, menus, UI trees, org charts

🧠 Interview Tip

Use Composite Pattern when the problem domain requires recursive traversal or group-leaf relationships.
Explain how it follows the Composite Principle: β€œClients should treat individual objects and composites uniformly.”


Top comments (0)