teacher
Sign in

Composite

Treat a single object and a group of objects through one interface, so trees such as folders and menus need no special-case code.

20 min3 interactive

The problem it solves

Many things in software form a tree: folders hold files and other folders, a menu holds items and sub-menus, a company holds employees and departments.

Without a pattern, every client writes this:

  • "If it is a file, do X. If it is a folder, loop over its children and do X to each."
  • The same if is repeated for size, print, delete, search.
  • A new kind of node means editing every one of those places.

Composite fixes this with one rule: the leaf (a thing with no children) and the container (a thing that holds children) implement the same interface. The client calls one method. The container forwards the call to its children, which may be containers themselves.

1 of 8