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
Composite
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
Composite is a structural design pattern. It arranges objects in a tree of parts and wholes and gives both the same type, the component.
A leaf has no parts and does the work itself. A composite holds components, passes each call on to them and combines what they answer.
Because the children of a composite have the type of the composite itself, trees of any depth come from two classes.
Why it exists
Without it, each client walks the tree by hand and asks at every node what kind it is. The loops are copied, and a new kind must be added to all of them.
With it, a client makes one call. New kinds of parts are new classes that the compiler forces to be complete.
Users think in groups: move the group, delete the folder, price the bundle. The pattern lets the code use the same sentence.
A short history
1974
Ritchie and Thompson describe the UNIX file system: directories are files that hold names of files and of other directories, to any depth.
1994
The book Design Patterns names Composite, with Component, Leaf and Composite as its roles.
1998
DOM Level 1 becomes a W3C Recommendation on 1 October. Documents, elements and texts are all Nodes, with the child methods on Node.
Words to know
- Component
- The common type of leaves and composites.
- Leaf
- A component without children. It ends the recursion.
- Composite
- A component that holds components and combines their answers.
- Part-whole hierarchy
- A tree in which each node is a part of the node above it.
- Transparent form
- Child methods are on Component. Uniform, checked at run time.
- Safe form
- Child methods are only on Composite. Checked by the compiler.
- Fold
- Combine the answers of all children into one.
- Cycle
- A node that is its own ancestor. The end of every recursion that never ends.
- Depth
- The number of levels. It decides how much call stack a recursion needs.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Client asks. One call on a component
Understand it
Start here
One question, asked of a part or of the whole
How heavy is a wooden star? Put it on a scale. How heavy is a mobile with twenty wooden figures, rods below rods below rods? Put it on the same scale. The scale has one hook and one question. It does not ask whether it carries one thing or many. The Composite pattern gives code the same comfort: one object and a whole tree of objects answer the same call.
The scale never learned the word rod. That is the point of the pattern.
A box of building blocks is another picture of it. One block is a leaf. A box can hold blocks and smaller boxes. Carry the big box to another room and everything inside moves too, and nobody opened it first.
Four roles
Component
The common type:
Entry,Employee,Shape. It declares the operations that make sense for one thing and for many.Leaf
A thing without parts:
File,Developer,Circle. It does the real work and ends the recursion.Composite
A thing with parts:
Folder,Manager,Group. It keeps children, passes the call on and combines the answers.Client
FileExplorer,PayrollReport,Canvas. It holds a Component and never asks which kind it is.
Why
What goes wrong without it
Somebody writes File and Folder as two unrelated classes. Every function that walks over a folder now has to know both kinds.
class File: def __init__(self, name, kb): self.name, self.kb = name, kbclass Folder: def __init__(self, name, files=(), folders=()): self.name, self.files, self.folders = name, list(files), list(folders) self.shortcuts = [] # added last monthclass Shortcut: def __init__(self, name): self.name, self.kb = name, 1def total(item): if isinstance(item, File): return item.kb if isinstance(item, Folder): kb = sum(f.kb for f in item.files) kb += sum(total(f) for f in item.folders) return kb # forgot item.shortcutsdef count(item): if isinstance(item, File): return 1 if isinstance(item, Folder): return len(item.files) + len(item.shortcuts) + sum(count(f) for f in item.folders)root = Folder("root", [File("a.txt", 10)], [Folder("docs", [File("b.txt", 20)])])root.shortcuts.append(Shortcut("b"))print("entries", count(root)) # 3, correctprint("KB", total(root)) # 30, should be 31print("KB of one shortcut", total(Shortcut("b"))) # NoneThe design that hurts
1/3Two unrelated classes
Folder keeps one list per kind. There is no word for an entry of any kind.
useshas (lives on)
Asking the component
- One call:
entry.size() - One list of components
- A new kind is one class
- Depth does not show in the client
Asking for the kind
if file,else if folderin every operation- One list per kind in the container
- A new kind touches every client
- Deep nesting needs a loop inside a loop
The idea
Put the recursion into the objects
Give parts and wholes one type. A leaf answers directly. A composite asks each child the same question and combines the answers. No loop knows the shape of the tree: each object knows one level.
The Composite pattern in general
1/4One type for both
The client knows Component. The interface holds only what makes sense for one thing and for many.
usesimplementshas (lives on)
What exists at run time
One call becomes seven
size: root, two folders and four files. The client made one of them.The rule in one line
Operations
How a composite combines answers
size is a sum, but many other operations fit. What changes is how the answers are put together, and what an empty composite says. Decide the second one on purpose.
| Operation | Leaf | Composite | Empty composite |
|---|---|---|---|
size, weight, price | own number | sum | 0 |
count | 1 | sum, plus 1 if it counts itself | 0 or 1, say which |
deepest or latest change | own value | maximum | nothing: use a default |
contains(name) | compare | any child, stop at the first | false |
isValid | check | all children | true |
draw, print | itself | itself, then the children in order | only itself |
move(dx, dy) | own position | forward to all | nothing |
bounds of a drawing | own rectangle | smallest rectangle around all | there is none: return null |
any of nothing is false and all of nothing is true. Check that this is what your rule means: is an empty order valid?Is this operation for the Component?
A decision
Where do add and remove live?
The oldest question about this pattern. If add is on the Component, every node looks the same, and calling it on a leaf fails while the program runs. If add is only on the Composite, the compiler protects you, and code that builds trees must hold a Composite.
A client calls file.add(other). How should the design answer?
BreaksComponent has add, the leaf ignores it
- How
- An empty
addinFile. - Limit
- The caller believes that the file is stored. Data is lost without a sound.
- Choose when
- Never.
WorksComponent has add, the leaf throws
- How
UnsupportedOperationException. This is called the transparent form.- Limit
- A mistake that a compiler could find is found by a user. It also breaks the promise of the type: see Liskov substitution.
- Choose when
- In tree editors where every node has the same menu, and in the DOM.
StrongOnly Composite has add
- How
Folder.addexists,File.adddoes not compile. This is called the safe form.- Limit
- Code that holds an
Entryand wants to add must ask for a folder once, at the edge. - Choose when
- The default. Building a tree and reading a tree are two jobs, and most clients only read.
Transparent against safe
| Transparent | Safe | |
|---|---|---|
| add and remove on | Component | Composite |
| Mistake found | while running | while compiling |
| Client that builds | holds any node | holds a Composite |
| Interface of a leaf | has methods that make no sense | only what it can do |
| Seen in | DOM Node.appendChild | AWT Container.add, Android ViewGroup.addView |
Choosing
When to use it and when not
Use it when
- The domain is a tree of parts and wholes
- Clients ask the same thing of one and of many
- Nesting depth is not known in advance
- New kinds of parts will come
- A rule set is made of rules: and, or, not
Leave it when
- The depth is fixed, such as order and order lines
- Leaf and whole share no operation
- The structure is a graph with shared nodes
- The tree lives in a database and is too big to load
- You need a common type only to have one
Composite or something smaller?
Where trees of parts appear
| Domain | Leaf | Composite | Shared operation |
|---|---|---|---|
| File system | file | folder | size, copy, delete |
| Screen | button, label | panel, window | draw, set visible, find at point |
| Organisation | developer, accountant | manager | salary cost, headcount |
| Restaurant menu | dish | menu, sub menu | print, find vegetarian |
| Drawing, CAD | line, circle | group | move, bounds |
| Document | paragraph | section, chapter | word count, render |
| Discount rules | one rule | all of, any of | applies(cart) |
| Shop bundle | product | bundle | price, weight, in stock |
JPanel panel = new JPanel();panel.add(new JButton("Click"));panel.add(new JLabel("Label"));panel.setVisible(false); // nothing of it is on the screenpanel.getComponent(0).isVisible(); // still true: the button's own flagJPanel is the composite, JButton and JLabel are used as leaves. Hiding the panel hides what is inside it, because children are painted by their parent. Their own visible flag stays true.What you get, and the price
Uniform treatment
One call for a leaf and for a tree. Clients stay short.
Recursive structure
Any depth with the same two classes.
Easy extension
A new kind of part is one class. Operations are harder: each new one touches all classes.
Too general
The type system no longer says which child belongs where. Rules such as "a menu holds no people" become checks in
add.
Summary
The whole topic in one minute.
One type for a part and the whole. The leaf answers, the composite asks each child and combines. The client holds one reference and makes one call.
Keep the common interface small: only what makes sense for a leaf. Put add and remove on the composite unless you need every node to look the same. Decide what an empty composite answers.
In production: one parent, no cycles, check before you move, cap the depth, store totals only with an audit, protect the operation and not the node, and let the database do the recursion over trees you do not hold.
- Composite is a tree in which a part and a whole have the same type.
- A leaf answers. A composite asks its children and combines.
- The composite is a Component and has many Components.
- Put on the Component only what makes sense for a leaf. Keep add and remove on the composite unless you have a reason.
- One parent each, no cycles, and decide what an empty composite answers.