Iterator
Access elements sequentially without exposing structure
Overview
The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation (list, stack, tree, etc.).
Key Concepts
Extracts traversal behavior of a collection into a separate object called an iterator
Supports single responsibility principle by separating traversal algorithms from data containers
Provides a standard interface for traversing any collection
Code Example
java
1public interface MyIterator<T> {
2 boolean hasNext();
3 T next();
4}
5
6public interface Aggregate<T> {
7 MyIterator<T> createIterator();
8}
9
10public class NameRepository implements Aggregate<String> {
11 public String[] names = {"John", "Jane", "Alice", "Bob"};
12
13 @Override
14 public MyIterator<String> createIterator() {
15 return new NameIterator();
16 }
17
18 private class NameIterator implements MyIterator<String> {
19 int index;
20
21 @Override
22 public boolean hasNext() {
23 return index < names.length;
24 }
25
26 @Override
27 public String next() {
28 if (this.hasNext()) {
29 return names[index++];
30 }
31 return null;
32 }
33 }
34}
35
36public class Client {
37 public static void main(String[] args) {
38 NameRepository namesRepository = new NameRepository();
39
40 for(MyIterator<String> iter = namesRepository.createIterator(); iter.hasNext();){
41 String name = iter.next();
42 System.out.println("Name : " + name);
43 }
44 }
45}