Iterator Pattern

# Iterator

- Purpose
- Structure
- Applications
- Consequences

## Purpose

- Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

## Structure

- 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.

## Applications

- to access an aggregate object's contents without exposing its internal representation.
- to support multiple traversals of aggregate objects.
- to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

## Consequences

- It supports variations in the traversal of an aggregate. Complex aggregates may be traversed in many ways. For example, code generation and semantic checking involve traversing parse trees. Code generation may traverse the parse tree inorder or preorder. Iterators make it easy to change the traversal algorithm: Just replace the iterator instance with a different one. You can also define Iterator subclasses to support new traversals.
- Iterators simplify the Aggregate interface. Iterator's traversal interface obviates the need for a similar interface in Aggregate, thereby simplifying the aggregate's interface.
- More than one traversal can be pending on an aggregate. An iterator keeps track of its own traversal state. Therefore you can have more than one traversal in progress at once.