Composite Pattern

March 31, 2026

Composite = Composite pattern removes this “type-checking” by making everything follow the same interface.

When you have tree-like structures, you often end up writing code like:

if (obj is Leaf) { ... }
else if (obj is Group) { ... }

1. Common interface

interface FileSystemComponent {
    void showDetails();
}

2. Leaf (Single object) - File

class File implements FileSystemComponent {
    private String name;

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

    public void showDetails() {
        System.out.println("File: " + name);
    }
}

3. Composite (group of objects) Directory

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

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

    public void add(FileSystemComponent component) {
        children.add(component);
    }

    public void remove(FileSystemComponent component) {
        children.remove(component);
    }

    public void showDetails() {
        System.out.println("Directory: " + name);
        for (FileSystemComponent component : children) {
            component.showDetails();
        }
    }
}

How to use

public class Main {
    public static void main(String[] args) {

        File file1 = new File("file1.txt");
        File file2 = new File("file2.txt");

        Directory folder1 = new Directory("Folder1");
        folder1.add(file1);

        Directory root = new Directory("Root");
        root.add(folder1);
        root.add(file2);

        root.showDetails();
    }
}

Output:

Directory: Root
Directory: Folder1
File: file1.txt
File: file2.txt

  • Adapter: use a old class into another new class, when call new method then call old method of old class inside.
  • Factory Method:
  • Bridge pattern: