AlgoViz

Composite pattern

medium 45 min

Composite 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

0:00 / 4:40

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

  1. 1974

    Ritchie and Thompson describe the UNIX file system: directories are files that hold names of files and of other directories, to any depth.

  2. 1994

    The book Design Patterns names Composite, with Component, Leaf and Composite as its roles.

  3. 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.

Step 1 of 3

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.

Noor builds a mobile
20

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.

Python
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")))   # None
Run it. A third kind, a shortcut, was added to the folder and to one of the two functions. The total is silently wrong.
Edit and run it in your browser

The design that hurts

filesFolder- files: List<File>- folders: List<Folder>+ getFiles()+ getFolders()File- kb: int

1/3Two unrelated classes

Folder keeps one list per kind. There is no word for an entry of any kind.

useshas (lives on)

The cost is kinds times operations: 3 kinds and 3 operations are 9 places to keep right.

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 folder in 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

Client+ holds a Component«interface»Component+ operation()

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)

The open diamond says the children could live on elsewhere. If the composite creates and destroys them, draw it filled.

What exists at run time

Three composites, four leaves. 250 + 100 = 350, 500 + 200 = 700, 350 + 700 = 1050 KB.

One call becomes seven

Seven objects, seven calls of size: root, two folders and four files. The client made one of them.

The rule in one line

size(x)={own valuex is a leaf∑c∈children(x)size(c)x is a composite\text{size}(x) = \begin{cases} \text{own value} & x \text{ is a leaf} \\ \sum_{c \in \text{children}(x)} \text{size}(c) & x \text{ is a composite} \end{cases}
The leaf is the base case of the recursion. n objects mean n calls, and the stack is as deep as the tree.

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.

OperationLeafCompositeEmpty composite
size, weight, priceown numbersum0
count1sum, plus 1 if it counts itself0 or 1, say which
deepest or latest changeown valuemaximumnothing: use a default
contains(name)compareany child, stop at the firstfalse
isValidcheckall childrentrue
draw, printitselfitself, then the children in orderonly itself
move(dx, dy)own positionforward to allnothing
bounds of a drawingown rectanglesmallest rectangle around allthere 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?

An export to another format usually ends at the last box. See Visitor.

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 add in File.
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.add exists, File.add does not compile. This is called the safe form.
Limit
Code that holds an Entry and 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

TransparentSafe
add and remove onComponentComposite
Mistake foundwhile runningwhile compiling
Client that buildsholds any nodeholds a Composite
Interface of a leafhas methods that make no senseonly what it can do
Seen inDOM Node.appendChildAWT 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

DomainLeafCompositeShared operation
File systemfilefoldersize, copy, delete
Screenbutton, labelpanel, windowdraw, set visible, find at point
Organisationdeveloper, accountantmanagersalary cost, headcount
Restaurant menudishmenu, sub menuprint, find vegetarian
Drawing, CADline, circlegroupmove, bounds
Documentparagraphsection, chapterword count, render
Discount rulesone ruleall of, any ofapplies(cart)
Shop bundleproductbundleprice, weight, in stock
Java
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 flag
A panel in Java Swing. JPanel 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.

Sources