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

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

clientClientrootFolderDocumentsFolderPicturesFoldervacation.jpg500profile.png200resume.pdfFilekb250cover.docxFilekb100

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

readerThread 1sum20writerThread 2AFolderholdsx 20BFolderholdsnothingsize()20

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

    major

    The pattern exists to remove this question.

    Wrong
    def total(e):    if isinstance(e, File): return e.kb    return sum(total(c) for c in e.children)
    Right
    def total(e):    return e.size()
  • A silent add on a leaf

    critical

    The caller believes that the child is stored.

    Wrong
    class File(Entry):    def add(self, e): pass
    Right
    class Folder(Entry):      # add lives only here    def add(self, e): ...
  • Forgetting the own value

    critical

    Managers are paid too.

    Wrong
    return sum(p.cost() for p in self._reports)
    Right
    return self.salary + sum(p.cost() for p in self._reports)
  • Handing out the list

    major

    Others add without any check, and parents are never set.

    Wrong
    def children(self):    return self._children
    Right
    def children(self):    return tuple(self._children)
  • Unlink before the check

    critical

    If the target refuses, the node is in no folder.

    Wrong
    del self._children[name]target.add(node)           # may raise
    Right
    target._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.