Composite pattern
medium 45 minComposite builds trees of parts and wholes in which one part and the whole tree have the same type.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: who asks whom, and how the answers climb.
Operations
Size of a folder
One call from the client becomes a call to each object below.
Step 1 of 8
A finished tree
Three folders and four files. The two pictures are shown inside their folder's card.
Step 1: A finished tree
class File(Entry): def size(self): return self._kbclass Folder(Entry): def size(self): return sum(c.size() for c in self._children.values())- Watch
- The call going down
- Result
- 350, 700, 1050
Nobody asks for a class name.
In the real world
The same composite pattern doing real jobs. Pick one and step through it.
A reader sums while a writer moves a file.
Step 1 of 3
The reader takes A
A holds x, 20 KB.
Step 1: The reader takes A
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Asking for the kind
majorThe pattern exists to remove this question.
Wrongdef total(e): if isinstance(e, File): return e.kb return sum(total(c) for c in e.children)Rightdef total(e): return e.size()A silent add on a leaf
criticalThe caller believes that the child is stored.
Wrongclass File(Entry): def add(self, e): passRightclass Folder(Entry): # add lives only here def add(self, e): ...Forgetting the own value
criticalManagers are paid too.
Wrongreturn sum(p.cost() for p in self._reports)Rightreturn self.salary + sum(p.cost() for p in self._reports)Handing out the list
majorOthers add without any check, and parents are never set.
Wrongdef children(self): return self._childrenRightdef children(self): return tuple(self._children)Unlink before the check
criticalIf the target refuses, the node is in no folder.
Wrongdel self._children[name]target.add(node) # may raiseRighttarget._check(node) # may raisedel self._children[name]target._link(node)
Interview tips
Small interface
- What a leaf can do.
- Return, do not print.
- add on the composite.
Keep it a tree
- One parent.
- Walk up for cycles.
- Links are leaves.
Mind the depth
- One frame per level.
- Cap input.
- Own stack if needed.
Totals
- Compute first.
- Store when reads win.
- Audit what you store.