Structural Design Pattern
Composite Design Pattern in Java
Treat individual objects and groups of objects uniformly through a tree structure.
In this lesson: Composite represents part-whole hierarchies so clients can use a leaf object and a collection of objects through the same interface.
Overview
Composite is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.
Implementation
interface FileSystemNode { int size(); }
final class FileNode implements FileSystemNode { private final int bytes; FileNode(int bytes) { this.bytes = bytes; } public int size() { return bytes; } }
final class Folder implements FileSystemNode { private final List<FileSystemNode> children = new ArrayList<>(); void add(FileSystemNode node) { children.add(node); } public int size() { return children.stream().mapToInt(FileSystemNode::size).sum(); } }
Folder folder = new Folder();
folder.add(new FileNode(120));
System.out.println(folder.size());
When should you use it?
Use Composite for menus, folders, organization charts, UI components, or any tree where leaves and containers share operations.
Next step: Continue with the Design Patterns course and explore the next pattern.