Skip to content
GDP for Noobs
☰ All patterns
StructuralIntermediate

Composite

Treat single items and groups of items the same way.

01

Explain it like I'm new

Real-life analogy

Boxes inside boxes

To weigh a shipment you don't care if something is a single item or a box full of smaller boxes. Ask anything its weight; boxes just add up what's inside.

😩 The problem

A folder contains files and other folders. Code that computes total size ends up full of type checks and special cases.

💡 The pattern

Give leaves (File) and containers (Folder) the same interface. Containers implement methods by delegating to their children, which recurses naturally.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import "fmt"
4
5// Node is shared by single items (File) AND groups of items (Folder).
6type Node interface {
7 Name() string
8 Size() int
9 Print(indent string)
10}
11
12// File is a "leaf": it has no children.
13type File struct {
14 name string
15 size int
16}
17
18func (f File) Name() string { return f.name }
19func (f File) Size() int { return f.size }
20func (f File) Print(indent string) { fmt.Printf("%s- %s (%d KB)\n", indent, f.name, f.size) }
21
22// Folder is a "composite": it holds other Nodes, which may be Files OR Folders.
23type Folder struct {
24 name string
25 children []Node
26}
27
28func (d *Folder) Add(n ...Node) *Folder { d.children = append(d.children, n...); return d }
29func (d *Folder) Name() string { return d.name }
30
31// Size asks every child for its size. Folders recurse automatically.
32func (d *Folder) Size() int {
33 total := 0
34 for _, c := range d.children {
35 total += c.Size()
36 }
37 return total
38}
39
40func (d *Folder) Print(indent string) {
41 fmt.Printf("%s+ %s/ (%d KB)\n", indent, d.name, d.Size())
42 for _, c := range d.children {
43 c.Print(indent + " ")
44 }
45}
46
47func main() {
48 root := (&Folder{name: "project"}).Add(
49 File{"go.mod", 1},
50 (&Folder{name: "cmd"}).Add(File{"main.go", 4}),
51 (&Folder{name: "internal"}).Add(
52 File{"server.go", 12},
53 (&Folder{name: "db"}).Add(File{"db.go", 8}, File{"db_test.go", 6}),
54 ),
55 )
56 root.Print("")
57 fmt.Println("Total:", root.Size(), "KB")
58}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

✅ Reach for it when…

  • •Trees: file systems, UI components, org charts, menus, ASTs.

🚫 Skip it when…

  • •Your data isn't hierarchical.

🐹 Go tip

Go's go/ast package models source code as a composite tree of ast.Node values.

🌍 You've already seen it in

go/ast nodes, html.Node trees and fs.FS directory walking.

04

Quick check

One question. No pressure.

Why does Folder.Size() not need to check whether a child is a File or a Folder?

Related: Iterator, Decorator