Composite Pattern
A lot of data in software is shaped like a tree. A folder holds files and other folders. A restaurant menu holds dishes and combo meals, and a combo holds dishes. A comment holds replies, which hold replies of their own. An app's menu bar holds commands and sub-menus.
Each of these has two kinds of things: single items (a file, a dish) and groups of items (a folder, a combo). Most of the time you want to ask both kinds the same question, "how big are you?" or "what do you cost?", without caring which kind you have. The Composite pattern gives both one shared interface. A single item answers directly; a group answers by asking each of its children and combining their answers.
🌳 In one sentence: give single objects and groups of objects one shared interface, so a group can be used anywhere a single object can, and an operation on a whole tree becomes one call on its root.
The Problem It Solves
Here is a small file system written without the pattern. File and Folder are unrelated classes, and every
function that walks the tree checks which one it has.
@dataclass
class File:
name: str
size: int
@dataclass
class Folder:
name: str
items: list[File | Folder] = field(default_factory=list)
def total_size(item: File | Folder) -> int:
if isinstance(item, File):
return item.size
return sum(total_size(child) for child in item.items)
def count_files(item: File | Folder) -> int:
if isinstance(item, File):
return 1
return sum(count_files(child) for child in item.items)
def print_tree(item: File | Folder, indent: int = 0) -> None:
if isinstance(item, File):
print(" " * indent + f"{item.name} ({item.size} B)")
return
print(" " * indent + item.name + "/")
for child in item.items:
print_tree(child, indent + 2)
This works, and for one function it would be fine. The trouble grows with every function you add.
Every operation repeats the same type check. total_size, count_files, print_tree, and later find,
delete and copy all start with isinstance(item, File). The knowledge of "what kinds of nodes exist" is copied
into each of them.
A new kind of node edits every function. Add a Symlink (size 0, never followed) or a ZipArchive (a file
that also has entries inside). Each function has to learn the new type. Miss one and you only find out at runtime:
every function treats anything that isn't a File as a folder, so a symlink crashes on item.items.
Callers have to know what they are holding. A UI that shows a size next to each row has to check the type
first. Rules about folders leak out of Folder into every caller.
The rules sit far from the data. "A folder's size is the sum of its children" is a fact about folders, but it
lives in a free function. Nobody reading Folder can see it.
⚠️ The smell to look for:
isinstanceortype ==checks that separate "one thing" from "a group of things", repeated at the top of several recursive functions. That is the cue for Composite.