GoF pattern • Behavioral
GoFBehavioralJava example
Iterator solves a specific structural problem in the design.
Traverse a collection without exposing its internal structure.
Pattern overview
GoF pattern
Traverse a collection without exposing its internal structure.
Intent
Provide a way to access elements of an aggregate sequentially without exposing how the aggregate is represented.
Problem
Clients need a traversal mechanism, but the collection implementation should remain encapsulated.
Solution
Expose iteration behavior through a dedicated iterator or iterable contract.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- Whenever traversal order or representation should be decoupled from client logic.
Tradeoffs
- Usually built into Java collections already, so custom iterators should be justified.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
public final class ReleaseTimeline implements Iterable<String> {
private final List<String> releases = List.of("Java 8", "Java 11", "Java 17", "Java 21");
@Override
public Iterator<String> iterator() {
return releases.iterator();
}
}