The 23 GoF design patterns and Dependency Injection – choose a pattern Abstract Factory design patternBuilder design patternFactory Method design patternPrototype design patternSingleton design patternAdapter design patternBridge design patternComposite design patternDecorator design patternFacade design patternFlyweight design patternProxy design patternChain of Responsibility design patternCommand design patternInterpreter design patternIterator design patternMediator design patternMemento design patternObserver design patternState design patternStrategy design patternTemplate Method design patternVisitor design patternDependency Injection design pattern

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 Iterator objects:
    • Define an interface for accessing and traversing the elements of an aggregate object (Iterator | next(),hasNext()).
    • Define classes (Iterator1,…) that implement the Iterator interface.
      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().
  • An aggregate provides an interface for creating an iterator (createIterator()).
  • Clients can use different Iterator objects 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(),… ).
  • 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?
  • 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 Aggregate interface to create an Iterator object.
    • Refers to the Iterator interface to access and traverse an Aggregate object.
  • Aggregate
    • Defines an interface for creating an Iterator object.
  • Aggregate1,…
    • Implement createIterator() by returning an instance of the corresponding iterator class (Iterator1).
  • Iterator
    • Defines an interface for accessing and traversing the elements of an Aggregate object.
  • Iterator1,…
    • Implement the Iterator interface.
    • 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.

Dynamic Object Collaboration

  • In this sample scenario, a Client object uses an Iterator1 object to traverse an Aggregate1 object front-to-back.
  • The interaction starts with the Client object that calls createIterator() on the Aggregate1 object.
  • Aggregate1 creates an Iterator1 object and returns (a reference to) it to the Client.
  • Thereafter, the Client uses the Iterator1 to traverse the elements of Aggregate1 front-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.