Iterator
Intent
Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
Participants
-
Aggregate -
defines an interface for creating an Iterator object.
-
Iterator -
defines an interface for accessing and traversing elements in an
Aggregate.
-
Concrete Aggregate -
implements the Iterator creation interface to return an instance of
the appropriate ConcreteIterator.
-
Concrete Iterator -
implements the Iterator interface, keeping track of its current
position in the aggregate.
Notes
-
The interface for some Java GUI classes, such as
Container
could be improved by providing access to children through iterators
rather than arrays.
Iterators are lighter weight and safer.
-
Some languages, such as Lisp and Scheme, are designed to process lists
through an iterator-like interface.
These languages make it easy to turn an original list into another
which
-
contains only the elements of the original list that meet some
criteria, or
-
contains elements of the original list converted by some converter
function.
Lists can also be created that do not have an underlying aggregate -
they just have an initial value and use a function to generate
successor values.
These lists are potentially infinite, but only have a small amount of
state.
All of these possibilities can be implemented in object-oriented
languages with the Iterator design pattern.
Examples
-
Enumeration
is the iterator interface that was used in the earliest Java versions.
-
Iterator
is a more streamlined iterator interface that was introduced in Java
version 1.2.
The inclusion of the remove() method is questionable.
It is usually implemented to throw an UnsupportedOperationException.