Polski

Article · Composite · Decorator

Composite – trees in which a leaf and a branch look the same

Composite lets you treat a single object and a whole group of objects in exactly the same way. A course curriculum example with modules and lessons in C#, TypeScript, Java, Go and Python.

By · · 11 min read

Menus with submenus, folders with files, a company department with teams, a course with modules and lessons – trees are everywhere. Composite means code working with a tree does not have to ask "is this a leaf or a branch?": both have the same interface, and a branch simply passes the call on to its children.

The problem: how long is this course?

A programming course platform shows the total video length next to each course. A course consists of lessons and sections, and sections may contain further sections – authors love "bonuses within bonuses". The first implementation:

course-duration.ts
function totalMinutes(items: (Lesson | Section)[]): number {
  let total = 0;
  for (const item of items) {
    if (item instanceof Lesson) total += item.minutes;
    else if (item instanceof Section) total += totalMinutes(item.children);
    // a new node type (Quiz? LiveSession?) means another branch – here and everywhere else
  }
  return total;
}

The same instanceof ladder shows up in printing the table of contents, counting lessons, exporting to PDF and tracking progress. Every new node type – a quiz, a live session – requires fixes in all those places.

The solution: a common interface for leaf and branch

We define a CurriculumItem interface with operations that make sense for every node: minutes() and print(). Lesson (the leaf) is responsible for itself. Section (the composite) holds a list of CurriculumItem children and implements the same methods by delegating to the children and summing the results. The client cannot tell one from the other.

Diagram: Composite structure

This is the tree from our example. The time of each section is the sum of its children's times – computed recursively, without a single instanceof:

Diagram: The example course as a tree – sections sum their children's time
RoleIn the exampleResponsibility
ComponentCurriculumItemthe common interface of leaves and composites
LeafLessondoes the actual work, has no children
CompositeSectionstores children, delegates to them and aggregates results
Clientthe course viewworks with components without knowing their kind

Implementation in five languages

In Java the interface is sealed – the compiler knows every kind of node, which helps with pattern matching in switch. In Go the leaf and the composite are ordinary structs satisfying the same interface, and in Python a Protocol is enough.

ICurriculumItem

Curriculum.cs
var course = new Section("Design Patterns",
[
    new Lesson("Welcome", 5),
    new Section("Creational", [new Lesson("Factory Method", 18), new Lesson("Builder", 22)]),
    new Section("Structural",
    [
        new Lesson("Adapter", 15),
        new Section("Bonus", [new Lesson("Composite in UI trees", 12)]),
    ]),
]);

course.Print();
Console.WriteLine($"Total: {course.Minutes} min"); // 72

// Component: a leaf and a branch look the same to the client.
public interface ICurriculumItem
{
    string Title { get; }
    int Minutes { get; }
    void Print(int depth = 0);
}

// Leaf: does the real work.
public sealed record Lesson(string Title, int Minutes) : ICurriculumItem
{
    public void Print(int depth = 0) =>
        Console.WriteLine($"{new string(' ', depth * 2)}- {Title} ({Minutes} min)");
}

// Composite: delegates to its children and aggregates their results.
public sealed class Section(string title, IReadOnlyList<ICurriculumItem> children) : ICurriculumItem
{
    public string Title => title;
    public int Minutes => children.Sum(child => child.Minutes);

    public void Print(int depth = 0)
    {
        Console.WriteLine($"{new string(' ', depth * 2)}+ {Title} ({Minutes} min)");
        foreach (var child in children) child.Print(depth + 1);
    }
}
curriculum.ts
// Component: a leaf and a branch look the same to the client.
interface CurriculumItem {
  readonly title: string;
  minutes(): number;
  print(depth?: number): void;
}

// Leaf: does the real work.
class Lesson implements CurriculumItem {
  constructor(readonly title: string, private readonly length: number) {}

  minutes(): number {
    return this.length;
  }

  print(depth = 0): void {
    console.log(`${"  ".repeat(depth)}- ${this.title} (${this.length} min)`);
  }
}

// Composite: delegates to its children and aggregates their results.
class Section implements CurriculumItem {
  constructor(readonly title: string, private readonly children: CurriculumItem[]) {}

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

  print(depth = 0): void {
    console.log(`${"  ".repeat(depth)}+ ${this.title} (${this.minutes()} min)`);
    this.children.forEach((child) => child.print(depth + 1));
  }
}

const course = new Section("Design Patterns", [
  new Lesson("Welcome", 5),
  new Section("Creational", [new Lesson("Factory Method", 18), new Lesson("Builder", 22)]),
  new Section("Structural", [
    new Lesson("Adapter", 15),
    new Section("Bonus", [new Lesson("Composite in UI trees", 12)]),
  ]),
]);

course.print();
console.log(`Total: ${course.minutes()} min`); // 72
Curriculum.java
import java.util.List;

// Component: a sealed interface lists every kind of node in the tree.
sealed interface CurriculumItem permits Lesson, Section {
    String title();
    int minutes();
    void print(int depth);
}

// Leaf: does the real work.
record Lesson(String title, int minutes) implements CurriculumItem {
    public void print(int depth) {
        System.out.println("  ".repeat(depth) + "- " + title + " (" + minutes + " min)");
    }
}

// Composite: delegates to its children and aggregates their results.
record Section(String title, List<CurriculumItem> children) implements CurriculumItem {
    public int minutes() {
        return children.stream().mapToInt(CurriculumItem::minutes).sum();
    }

    public void print(int depth) {
        System.out.println("  ".repeat(depth) + "+ " + title + " (" + minutes() + " min)");
        children.forEach(child -> child.print(depth + 1));
    }
}

public class Curriculum {
    public static void main(String[] args) {
        CurriculumItem course = new Section("Design Patterns", List.of(
            new Lesson("Welcome", 5),
            new Section("Creational", List.of(new Lesson("Factory Method", 18), new Lesson("Builder", 22))),
            new Section("Structural", List.of(
                new Lesson("Adapter", 15),
                new Section("Bonus", List.of(new Lesson("Composite in UI trees", 12)))))));

        course.print(0);
        System.out.println("Total: " + course.minutes() + " min"); // 72
    }
}
curriculum.go
package main

import (
	"fmt"
	"strings"
)

// CurriculumItem is the component: a leaf and a branch look the same to the client.
type CurriculumItem interface {
	Minutes() int
	Print(depth int)
}

// Lesson is a leaf: it does the real work.
type Lesson struct {
	Title  string
	Length int
}

func (l Lesson) Minutes() int { return l.Length }

func (l Lesson) Print(depth int) {
	fmt.Printf("%s- %s (%d min)\n", strings.Repeat("  ", depth), l.Title, l.Length)
}

// Section is the composite: it delegates to its children and aggregates their results.
type Section struct {
	Title    string
	Children []CurriculumItem
}

func (s Section) Minutes() int {
	total := 0
	for _, child := range s.Children {
		total += child.Minutes()
	}
	return total
}

func (s Section) Print(depth int) {
	fmt.Printf("%s+ %s (%d min)\n", strings.Repeat("  ", depth), s.Title, s.Minutes())
	for _, child := range s.Children {
		child.Print(depth + 1)
	}
}

func main() {
	course := Section{"Design Patterns", []CurriculumItem{
		Lesson{"Welcome", 5},
		Section{"Creational", []CurriculumItem{Lesson{"Factory Method", 18}, Lesson{"Builder", 22}}},
		Section{"Structural", []CurriculumItem{
			Lesson{"Adapter", 15},
			Section{"Bonus", []CurriculumItem{Lesson{"Composite in UI trees", 12}}},
		}},
	}}
	course.Print(0)
	fmt.Printf("Total: %d min\n", course.Minutes()) // 72
}
curriculum.py
from dataclasses import dataclass, field
from typing import Protocol


class CurriculumItem(Protocol):
    """Component: a leaf and a branch look the same to the client."""

    def minutes(self) -> int: ...
    def print_tree(self, depth: int = 0) -> None: ...


@dataclass(frozen=True)
class Lesson:
    """Leaf: does the real work."""

    title: str
    length: int

    def minutes(self) -> int:
        return self.length

    def print_tree(self, depth: int = 0) -> None:
        print(f"{'  ' * depth}- {self.title} ({self.length} min)")


@dataclass(frozen=True)
class Section:
    """Composite: delegates to its children and aggregates their results."""

    title: str
    children: list[CurriculumItem] = field(default_factory=list)

    def minutes(self) -> int:
        return sum(child.minutes() for child in self.children)

    def print_tree(self, depth: int = 0) -> None:
        print(f"{'  ' * depth}+ {self.title} ({self.minutes()} min)")
        for child in self.children:
            child.print_tree(depth + 1)


if __name__ == "__main__":
    course = Section("Design Patterns", [
        Lesson("Welcome", 5),
        Section("Creational", [Lesson("Factory Method", 18), Lesson("Builder", 22)]),
        Section("Structural", [
            Lesson("Adapter", 15),
            Section("Bonus", [Lesson("Composite in UI trees", 12)]),
        ]),
    ])
    course.print_tree()
    print(f"Total: {course.minutes()} min")  # 72

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Transparency or safety?
  • Step by step
  • When to use it and when not to
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in