Pattern · Core

Composite

Build a tree of part-and-whole objects, then treat a single leaf and a whole branch THE SAME way through one interface.

Asked atAmazonGoogleFigma
step 1 / 9
1/2Leaf and branch, one type
children*
«interface»
FileItem
+ size(): int
File
- bytes: int
+ size()
Folder
- children: List
+ size()
+ add(item)
Leaf and branch, one type
1interface FileItem { int size(); }
2class File implements FileItem { ... }
3class Folder implements FileItem {
4 List<FileItem> children; // files AND folders
5}

FileItem is the shared contract — anything in the tree can report its size().