Iterator Design Pattern
Behavioral pattern. Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.
The Iterator design pattern solves problems like: How can the elements of an aggregate object be accessed and traversed without exposing its underlying representation?
Open in the interactive referenceDownload the PDF reference
Problem
The Iterator design pattern solves problems like:
How can the elements of an aggregate object be accessed
and traversed
without exposing its underlying representation?
See Applicability section for all problems Iterator can solve.
See Solution section for how Iterator solves the problems.
-
One way to solve this problem is
to extend the aggregate interface
with operations for access and traversal.
For example, traversing front-to-back:next(),hasNext(). -
This commits the aggregate object to particular
access and traversal operations and
makes it impossible to add new operations
later without having to change the aggregate
interface.
For example, traversing back-to-front:previous(),hasPrivious().
"But you probably don't want to bloat the List [Aggregate] interface with operations for different traversals, even if you could anticipate the ones you will need." [GoF, p257] - That's the kind of approach to avoid if we want to define new access and traversal operations without having to change the aggregate interface.
-
For example, an aggregate object like a list, set, or other kind of
collection.
It should be possible to access and traverse the elements of a collection in different ways without knowing (depending on) its representation (data structures). See Sample Code / Example 2.
Solution
The Iterator design pattern provides a solution:
Encapsulate the access and traversal of an aggregate
in a separate Iterator object.
Clients request an
Iterator object from an aggregate
(createIterator())
and use it to access and traverse the aggregate.
Describing the Iterator design in more detail is the
theme of the following sections.
See Applicability section for all problems Iterator can solve.
- "The key idea in this pattern is to take the responsibility for access and traversal out of the list [aggregate] object and put it into an iterator object." [GoF, p257] [BGI]
-
Define separate
Iteratorobjects:-
Define an interface for accessing and traversing
the elements of an aggregate object
(
Iterator | next(),hasNext()). -
Define classes (
Iterator1,…) that implement theIteratorinterface.
An iterator is usually implemented as inner class of an aggregate class.
This enables the iterator to access the internal data structures of the aggregate (see Implementation). -
New access and traversal operations can be added
by defining new iterators.
For example, traversing back-to-front:previous(),hasPrevious().
-
Define an interface for accessing and traversing
the elements of an aggregate object
(
-
An aggregate provides an interface
for creating an iterator
(
createIterator()). -
Clients can use
different
Iteratorobjects to access and traverse an aggregate object in different ways. Multiple traversals can be in progress on the same aggregate object (simultaneous traversals).
Background Information
-
For example, the Java Collections Framework
provides
-
a general purpose iterator
(next(),hasNext(),remove()) -
and an extended listIterator
(next(),hasNext(),previous(),hasPrevious(),remove(),…).
-
a general purpose iterator
-
Consequently, there are two factory methods for creating an iterator
(iterator() and listIterator()).
Applicability
Design Problems
-
Accessing and Traversing Object Structures
-
How can the elements of an aggregate object
be accessed and traversed
without exposing its underlying representation? -
How can new traversal operations be defined for
an aggregate object
without changing its interface?
-
How can the elements of an aggregate object
be accessed and traversed
-
Performing Different Traversals
- How can different traversals be performed on an aggregate object?
- How can multiple traversals be pending on the same aggregate object (simultaneous traversals)?
Structure
Static Class Structure
-
Client-
Refers to the
Aggregateinterface to create anIteratorobject. -
Refers to the
Iteratorinterface to access and traverse anAggregateobject.
-
Refers to the
-
Aggregate-
Defines an interface for
creating an
Iteratorobject.
-
Defines an interface for
creating an
-
Aggregate1,…-
Implement
createIterator()by returning an instance of the corresponding iterator class (Iterator1).
-
Implement
-
Iterator-
Defines an interface
for accessing and traversing
the elements of an
Aggregateobject.
-
Defines an interface
for accessing and traversing
the elements of an
-
Iterator1,…-
Implement the
Iteratorinterface. - An iterator is usually implemented as inner class of an aggregate class so that it can access the internal (private) data structures of the aggregate.
-
Implement the
Dynamic Object Collaboration
-
In this sample scenario,
a
Clientobject uses anIterator1object to traverse anAggregate1object front-to-back. -
The interaction starts with the
Clientobject that callscreateIterator()on theAggregate1object. -
Aggregate1creates anIterator1object and returns (a reference to) it to theClient. -
Thereafter,
the
Clientuses theIterator1to traverse the elements ofAggregate1front-to-back (while iterator.hasNext(): iterator.next()). -
See also Sample Code / Example 1.
Sample Code 1
Basic Java code for implementing the sample UML diagrams.
1 package com.sample.iterator.basic;
2 public class Client {
3 // Running the Client class as application.
4 public static void main(String[] args) {
5 // Setting up an aggregate.
6 Aggregate<String> aggregate = new Aggregate1<String>(3);
7 aggregate.add(" ElementA ");
8 aggregate.add(" ElementB ");
9 aggregate.add(" ElementC ");
10 //
11 // Creating an iterator.
12 Iterator<String> iterator = aggregate.createIterator();
13 //
14 System.out.println("Traversing the aggregate front-to-back:");
15 while (iterator.hasNext()) {
16 System.out.println(iterator.next());
17 }
18 }
19 }
Traversing the aggregate front-to-back:
ElementA
ElementB
ElementC
1 package com.sample.iterator.basic;
2 public interface Aggregate<E> {
3 // ...
4 Iterator<E> createIterator();
5 boolean add(E element);
6 }
1 package com.sample.iterator.basic;
2 public interface Iterator<E> {
3 E next();
4 boolean hasNext();
5 }
1 package com.sample.iterator.basic;
2 import java.util.NoSuchElementException;
3 public class Aggregate1<E> implements Aggregate<E> { // E = Type parameter
4 // Hiding the representation.
5 private Object[] elementData; // represented as object array
6 private int idx = 0;
7 private int size;
8 //
9 public Aggregate1(int size) {
10 if (size < 0)
11 throw new IllegalArgumentException("size: " + size);
12 this.size = size;
13 elementData = new Object[size];
14 }
15 public boolean add(E element) {
16 if (idx < size) {
17 elementData[idx++] = element;
18 return true;
19 } else
20 return false;
21 }
22 public int getSize() {
23 return size;
24 }
25 // Factory method for instantiating Iterator1.
26 public Iterator<E> createIterator() {
27 return new Iterator1<E>();
28 }
29 //
30 // Implementing Iterator1 as inner class.
31 //
32 private class Iterator1<E> implements Iterator<E> {
33 // Holds the current position in the traversal.
34 private int cursor = 0; // index of next element to return
35 //
36 public boolean hasNext() {
37 return cursor < size;
38 }
39 public E next() { // E = Type of element returned by this method
40 if (cursor >= size)
41 throw new NoSuchElementException();
42 return (E) elementData[cursor++]; // cast from Object to E
43 }
44 }
45 }
Not included on this page: Intent, Motivation, Consequences, Implementation, Related Patterns. See the GoF Design Patterns Reference (PDF) for the complete description.