Iterator
16 Mar 2022Intent
Provide a way to access the elements of an aggregate object sequentially without exposing it's underlying representation.
Also known as
Cursor
Applicability
Use the Iterator patter:
- To access an aggregate object's contents without exposing it's internal representation.
- To support multiple traversals of aggregate objects.
- To provide a uniform interface for traversing different aggregate structures, i.e. to support polymorphic iteration.
Structure
Participants
- Iterator: defines an interface for accessing and traversing elements.
- ConcreteIterator: implements the Iterator interface, keeps track of the current position in the traversal of the aggregate.
- Aggregate: defines an interface for creating an Iterator object.
- ConcreteAggregate: implements the Iterator creation interface to return an instance of the proper ConcreteIterator.
Collaborations
A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal.
Consequences
The Iterator pattern has the below consequences:
- It supports variations in the traversal of an aggregate.
- Iterators simplify the Aggregate interface.
- More than one traversal can be pending on an aggregate.
Sample Code
Related Patterns
- Composite: Iterators are often applied to recursive structures such as Composites.
- Factory Method: Polymorphic iterators rely on factory methods to instantiate the appropriate Iterator subclass.
- Memento is often used in conjunction with the Iterator pattern. An Iterator can use a memento to capture the state of an iteration. The Iterator stores the memento internally.