Design Patterns

Pattern 8 of 23, Structural family

Composite

Compose objects into tree structures and treat leaves and groups uniformly.

The problem

Computing the size of a folder: it contains files and other folders, themselves nested. The if (item instanceof Folder) checks keep piling up.

The solution

Define a common interface (size()) implemented by both the leaf (File) and the composite (Folder). The composite delegates recursively to its children.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The client calls size() on the root without knowing what it contains.
  2. The folder delegates to each of its children.
  3. app.ts โ€” 4 KB โ†’ Folder src/: 4
  4. A subfolder is treated exactly like a file.
  5. Folder utils/ โ†’ a.ts โ€” 2 KB: size()
  6. a.ts โ€” 2 KB โ†’ Folder utils/: 2
  7. Folder utils/ โ†’ b.ts โ€” 1 KB: size()
  8. b.ts โ€” 1 KB โ†’ Folder utils/: 1
  9. Folder utils/ = 3 KB โ†’ Folder src/: 3
  10. Result aggregated by recursion, without a single if on the type.

An analogy

An army: an order given to a division flows down to the brigades, then to the soldiers, without the general handling each one.

When to use it

  • Tree structures: files, menus, DOM, org charts
  • Treating a group as a single element
  • Shopping cart with product bundles

Pros and cons

Pros

  • Simple client code, natural recursion
  • New node types are easy to add

Cons

  • Common interface can end up too general
  • Hard to restrict which child types are allowed

Implementations

The same example, written idiomatically in each language.

Composite in Python

composite.py 32 lines
from abc import ABC, abstractmethod


class Node(ABC):
    @abstractmethod
    def size(self) -> int: ...


class File(Node):
    def __init__(self, name: str, kb: int):
        self.name, self.kb = name, kb

    def size(self): return self.kb


class Folder(Node):
    def __init__(self, name: str):
        self.name, self.children = name, []

    def add(self, *nodes: Node):
        self.children.extend(nodes)
        return self

    def size(self):
        return sum(c.size() for c in self.children)


src = Folder("src").add(
    File("app.ts", 4),
    Folder("utils").add(File("a.ts", 2), File("b.ts", 1)),
)
print(src.size())  # 7

Composite in TypeScript

composite.ts 23 lines
interface FsNode { size(): number; }

class FileNode implements FsNode {
  constructor(public name: string, private kb: number) {}
  size() { return this.kb; }
}

class Folder implements FsNode {
  private children: FsNode[] = [];
  constructor(public name: string) {}

  add(...nodes: FsNode[]) { this.children.push(...nodes); return this; }

  size(): number {
    return this.children.reduce((sum, c) => sum + c.size(), 0);
  }
}

const src = new Folder("src").add(
  new FileNode("app.ts", 4),
  new Folder("utils").add(new FileNode("a.ts", 2), new FileNode("b.ts", 1)),
);
src.size(); // 7

Composite in Java

composite.java 23 lines
interface FsNode { int size(); }

record FileNode(String name, int kb) implements FsNode {
    public int size() { return kb; }
}

class Folder implements FsNode {
    private final List<FsNode> children = new ArrayList<>();

    Folder add(FsNode... nodes) {
        children.addAll(List.of(nodes));
        return this;
    }

    public int size() {
        return children.stream().mapToInt(FsNode::size).sum();
    }
}

int total = new Folder()
        .add(new FileNode("app.ts", 4),
             new Folder().add(new FileNode("a.ts", 2), new FileNode("b.ts", 1)))
        .size(); // 7

Composite in C#

composite.cs 20 lines
interface IFsNode { int Size(); }

record FileNode(string Name, int Kb) : IFsNode
{
    public int Size() => Kb;
}

class Folder : IFsNode
{
    private readonly List<IFsNode> _children = [];

    public Folder Add(params IFsNode[] nodes) { _children.AddRange(nodes); return this; }

    public int Size() => _children.Sum(c => c.Size());
}

var total = new Folder()
    .Add(new FileNode("app.ts", 4),
         new Folder().Add(new FileNode("a.ts", 2), new FileNode("b.ts", 1)))
    .Size(); // 7

Composite in PHP

composite.php 27 lines
interface FsNode { public function size(): int; }

final class File implements FsNode
{
    public function __construct(public string $name, private int $kb) {}
    public function size(): int { return $this->kb; }
}

final class Folder implements FsNode
{
    private array $children = [];

    public function add(FsNode ...$nodes): static
    {
        array_push($this->children, ...$nodes);
        return $this;
    }

    public function size(): int
    {
        return array_sum(array_map(fn(FsNode $c) => $c->size(), $this->children));
    }
}

echo (new Folder())
    ->add(new File('app.ts', 4), (new Folder())->add(new File('a.ts', 2), new File('b.ts', 1)))
    ->size(); // 7

Composite in Go

composite.go 25 lines
type Node interface{ Size() int }

type File struct {
    Name string
    KB   int
}

func (f File) Size() int { return f.KB }

type Folder struct{ Children []Node }

func (d *Folder) Add(n ...Node) *Folder {
    d.Children = append(d.Children, n...)
    return d
}

func (d *Folder) Size() (total int) {
    for _, c := range d.Children {
        total += c.Size()
    }
    return
}

src := (&Folder{}).Add(File{"app.ts", 4}, (&Folder{}).Add(File{"a.ts", 2}, File{"b.ts", 1}))
fmt.Println(src.Size()) // 7

Frequently asked questions

What is the Composite design pattern?

Compose objects into tree structures and treat leaves and groups uniformly. Define a common interface (size()) implemented by both the leaf (File) and the composite (Folder). The composite delegates recursively to its children.

When should you use the Composite pattern?

Tree structures: files, menus, DOM, org charts; Treating a group as a single element; Shopping cart with product bundles.

What are the pros and cons of the Composite pattern?

Pros: Simple client code, natural recursion; New node types are easy to add. Cons: Common interface can end up too general; Hard to restrict which child types are allowed.