Iterator
Category
Behavioral pattern
Problem
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Useful when the collection has complex internal structure.
Solution
- Create an Iterator interface with
next(),hasNext(), and optionallyremove()methods - Concrete iterators traverse the collection, maintaining their own position
- The collection provides an
iterator()method that returns an iterator
Structure
- Iterator: Interface for accessing and traversing elements
- ConcreteIterator: Implements Iterator; maintains traversal state
- Aggregate: Interface for creating an iterator
- ConcreteAggregate: Returns a concrete iterator
Key Benefits
- Uniform traversal — Same interface works for any collection type
- Multiple traversals — Multiple iterators can traverse simultaneously
- Encapsulation — Collection’s internal structure is hidden
- Flexibility — Different iteration strategies (forward, reverse, filtered)
Trade-offs
- Overhead — Creating iterator objects for simple traversals
- Interface complexity — Many iterator variants (forward, reverse, filtered, etc.)
When to Use
- You want to access a collection’s contents without exposing its representation
- You want to support multiple traversals of a collection
- You want a uniform interface for traversing different collections