Provide a way to traverse the elements in an aggregate object, without exposing its underlying representation.
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.
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.
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..
- Keeps interface to the aggregate simple. Interface for traversal is in the iterator class.
- Supports variety of traversal mechanisms over a given aggregate.
- Supports multiple simultaneous traversals over an aggregate.
A code example of external and internal iterators are provided in the file Iterator.zip.
Implementation Considerations
Variations
- Who defines traversal algorithm?
- Iterator - reusable, can define different traversal mechanisms on same aggregate
- Aggregate - traversal may require access to private data
- Polymorphic iterators in C++ must be allocated dynamically, through factory method. Client code is responsible for deleting them, which could lead to memory leaks.
- Composite iterators may be difficult to implement, because iterator must maintain path through a complex structure.
- Robust iterators - Ensure that modification to aggregate won't interfere with ongoing traversal.
- External Iterator: The client controls the traversal.
- Java Iterator is external.
- Internal Iterator: The iterator controls the traversal. Client hands iterator some operation to perform on each element in aggregate. Iterator traverses aggregate and applies operation to each element.
- Composite: Iterators are used to traverse composite objects.
- Factory Method: Used in polymorphic iterators to create the appropriate type of iterator for an aggregate.
Modified:
21-Feb-2004
Gary Pollice