Design Patterns
Composite
Working with a composite touches every item once. So it takes O(n) time, where n is the total number of items, including nested ones.
The idea, in plain English
Composite works like folders on your computer. A folder can hold files, but it can also hold more folders, which hold more files and folders. Composite lets you treat one single file and a whole folder full of files the exact same way. Ask either one 'how big are you?' and each figures out its own answer.
How it works
- 1You give both the simple items (files) and the containers (folders) the same method name, like getSize().
- 2A simple item just returns its own answer directly.
- 3A container loops over everything inside it — files or more folders — and adds up their answers. This works no matter how deeply things are nested.
When you'd use it
Use this when you have tree-shaped data — file systems, UI components holding other components, or org charts — and want to treat a single item and a whole group the same way.
Common beginner mistakes
- Don't give containers and simple items different method names. That forces you to check 'is this a file or a folder?' everywhere, instead of calling the same method on both.
- Don't let a folder accidentally contain itself. That causes infinite loops when you try to add up its size.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
resume.pdf size: 200
Photos folder size: 500
Documents folder size: 700Not sure this is the right topic? See the learning paths → or where this leads →