CSE Roadmap

Common tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

Using both

Composite plus iterator, and where else they appear.

Using both

Together, the patterns give a tidy design. The composite holds the structure, and an iterator gives a way to run over it. Code that finds all files above a size, or counts nodes, becomes a loop.

for (Node n : root) {
    if (n.size() > 6) System.out.println(n.name());
}

Other places the pair appears: a menu bar with menus and items, a graphics editor with shapes and groups of shapes, an organisation chart with people and teams, and an expression tree in a calculator. The Command pattern's macro (module 4) is a composite of commands. A chess or board game design may group squares into rows.

Two alternatives to a hand-written iterator are worth knowing. A recursive method such as size() is simpler when you only need one fixed operation. A Stream built from the tree is concise in modern Java. Write an iterator when callers need to walk lazily, stop early, or run several walks.

Composite has a sibling: the visitor pattern, which adds new operations to a tree without changing its classes. It is beyond this level, and is worth a look if a design round gives you a tree with many separate operations.

Common mistake

Letting a leaf and a composite behave very differently under the same interface, so that callers still need instanceof. If they do, the common interface is wrong.

Interview angle

Answer in your head first, then open it.

What is the Composite pattern?

A leaf and a group share one interface, so clients treat a single object and a tree of objects alike.

What is the Iterator pattern?

An object that walks a collection one element at a time, keeping its own position, so the collection's structure stays hidden.

Where would you use them?

A file system, a menu, an organisation chart, or a group of shapes in a drawing tool.

Check yourself: 1. Which pattern holds the structure and which one walks it? 2. When is a plain recursive method enough?

Words you will meet

Word Meaning
Composite An object that holds other objects with the same interface
Leaf A single object with no children
Part-whole hierarchy A tree where groups contain parts and other groups
Iterator An object that visits elements one at a time
Traversal A walk through every element of a structure