All PatternsStructural
Composite
Composes objects into tree structures to represent part-whole hierarchies.
File systemsUI hierarchiesOrganization charts
Understanding Composite
The Composite pattern organizes objects into tree structures to represent part-whole hierarchies. Both individual objects (leaves) and groups of objects (composites) implement the same interface, so client code can treat a single file the same way it treats an entire folder. In Go, this is implemented via a shared interface with a recursive method — the composite's implementation iterates over its children and aggregates results. This pattern is the foundation of file systems, UI component trees, and organizational hierarchies.
Key Concepts
- •Component interface — shared interface that both leaves and composites implement, enabling uniform treatment
- •Leaf — end objects with no children that perform the actual work (e.g., a File)
- •Composite — container that holds child components and delegates operations to them recursively (e.g., a Folder)
- •Recursive composition — composites can contain other composites, enabling arbitrarily deep tree structures
When to Use
✅ Use when
- • You need to represent tree-like hierarchies (files, UI, org charts)
- • Client code should treat groups and individuals the same way
- • You need recursive operations across the entire tree (size, count, render)
- • The depth of nesting is unknown at compile time
⚠️ Avoid when
- • Your data is flat — a simple slice or map is sufficient
- • Leaf and composite behaviors are very different and hard to unify
- • You need strict type checking between different node types
Structure
<<Component>> Operation()
↓ implements
Leaf
Composite
children: []Component
How It Works
📁 Root
📄 File1
📁 SubFolder
📄 File2
Leaf
Composite
1
Leaf Nodes
Individual objects that perform actual work.
1 / 4
Basic Implementation
File system with files and folders:
main.go
Loading editor...
Real-World Example: Organization Hierarchy
Employee hierarchy with salary calculations:
main.go
Loading editor...