Iterator Pattern

The Iterator Pattern is used to get a way to access the elements of a collection object in sequential manner without any need to know its underlying representation. The C++ and Java standard library abstraction utilize it to decouple collection classes and algorithms.

Intent

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Implementation

Class Diagram of Iterator Pattern

Here is an example using Iterator Pattern to retrieve the names of all the pets in the pet repository.

Create interfaces.

1
2
3
4
5
6
// Iterator.java
public interface Iterator {
boolean hasNext();
Object next();
}

1
2
3
4
5
// Container.java
public interface Container {
Iterator getIterator();
}

Create concrete class implementing the Container interface. This class has inner class NameIterator implementing the Iterator interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// PetRepository.java
public class PetRepository implements Container {
public String pets[] = {
"Tyrannosaurus Rex",
"Stegosaurus",
"Velociraptor",
"Triceratops",
"Pterosauria",
"Ichthyosaur",
"Tanystropheus"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index = 0;
@Override
public boolean hasNext() {
return index < pets.length;
}
@Override
public Object next() {
if (hasNext()) {
return pets[index++];
}
return null;
}
}
}

Let’s print out our lovely pets ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
// ClientMain.java
public class ClientMain {
public static void main(String[] args) {
PetRepository pets = new PetRepository();
for (Iterator iter = pets.getIterator(); iter.hasNext(); ) {
String name = (String) iter.next();
System.out.println(name);
}
}
}

Output

Tyrannosaurus Rex
Stegosaurus
Velociraptor
Triceratops
Pterosauria
Ichthyosaur
Tanystropheus

Reference

TutorialsPoint
OODesign