Pattern: Iterator

Synopsis

Provide a way to traverse the elements in an aggregate object, without exposing its underlying representation.

Context

Aggregate objects such as lists should provide an interface to iterate over them.  There may be different ways you want to traverse the object, such as filtering over a subset of items in the aggregate.  You may also need to support multiple simultaneous traversals over the same aggregate.

Forces

Providing access through the aggregate object could expose client to internal structure of aggregate.   Providing for different kinds of traversals, or multiple simulaneous traversals could lead to a bloated public interface in the aggregate.

Solution

The iterator pattern shifts responsibility for traversal out of the aggregate object and into an iterator class.  The iterator class knows about the aggregate object and provides the public interface for accessing elements in the aggregate.  The iterator object is responsible for keeping track of the current element in the traversal.  Client requests an iterator from the aggregate object, and then uses the iterator to traverse the aggregate..


Iterator Class Diagram

Consequences

Implementation

A code example of external and internal iterators are provided in the file Iterator.zip.

Implementation Considerations

Variations

Related Patterns


Modified: 21-Feb-2004
Gary Pollice