Iterator
Intent
Traverses elements of a collection without exposing its underlying representation.
Problem
Clients need to walk a tree depth-first, breadth-first or randomly without knowing how it's stored.
Solution
Extract traversal into iterator objects; most languages now build this in (foreach, for…of, range, generators).
Real-world analogy
Touring a city: with a paper map, a guide or an app. Same sights, different ways to walk through them.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Iterator — Iterator declares traversal operations.
- 2ConcreteIterator — Concrete Iterators implement one traversal algorithm and track their own position.
- 3IterableCollection — Iterable Collection declares a method that returns a compatible iterator.
- 4ConcreteCollection — Concrete Collections return a new iterator each time a client asks.
- 5Client — Client works through the interfaces, so collections and iterators stay interchangeable.
Code example
Applicability
Use Iterator when hiding a complex data structure.
Use Iterator when reducing duplicated traversal code.
Pros and cons
Pros
- Single Responsibility and Open–Closed
- Parallel iteration over the same collection
Cons
- Overkill for simple collections
Relations with other patterns
Check yourself
Clients loop over a custom tree depth-first or breadth-first without knowing how it is stored.
Saved in this browser only. Part of Behavioral patterns (0/11).