Structural Design Pattern · Java

Composite Design Pattern in Java

Treat individual objects and groups of objects through one common interface.

What is Composite?

Composite builds a tree structure. A leaf performs work, while a composite contains and delegates to other components.

Beginner-friendly Java example

The following example shows the central idea of this pattern in a small, practical scenario.

interface FileSystemItem {
    void print(String indent);
}

class FileItem implements FileSystemItem {
    public void print(String indent) {
        System.out.println(indent + "file");
    }
}

class Folder implements FileSystemItem {
    private final List<FileSystemItem> items = new ArrayList<>();

    void add(FileSystemItem item) {
        items.add(item);
    }

    public void print(String indent) {
        for (FileSystemItem item : items) {
            item.print(indent + "  ");
        }
    }
}

Benefits and trade-offs

Benefits
  • Separates responsibilities clearly.
  • Improves flexibility as the application grows.
  • Encapsulates structural complexity.
Trade-offs
  • Can introduce extra wrapper classes.
  • Choose the pattern only when the complexity is real.

When should you use it?

  • File and folder trees
  • Organization hierarchies
  • Menus containing submenus
Key takeawayTreat individual objects and groups of objects through one common interface. Start with the smallest structure that solves the coupling or composition problem.