The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The Iterator Pattern separates the traversal logic from the collection itself. The client uses the iterator interface rather than accessing the collection directly, so different collection types can be iterated uniformly.
- Iterator: Interface defining
hasNext()andnext()methods for traversal - ConcreteIterator: Implements the iterator for a specific collection type
- Aggregate: Interface defining
createIterator()to produce an iterator - ConcreteAggregate: The collection that returns a concrete iterator for itself
Demonstrates a custom iterator implementation. Each menu type (DinnerMenu, PancakeHouseMenu) provides its own iterator — DinnerMenu uses an array-backed custom iterator, while PancakeHouseMenu uses an ArrayList.
See the MenuExample README for details on compiling and running.
Demonstrates the same menu pattern using Java's built-in java.util.Iterator interface. Adds a CafeMenu backed by a HashMap, showing how the iterator pattern unifies traversal across different underlying data structures.
See the MenuJavaUtilsExample README for details on compiling and running.
From the project root:
javac -d out IteratorPattern/MenuExample/*.javaOr for the Java built-in iterator example:
javac -d out IteratorPattern/MenuJavaUtilsExample/*.javajava -cp out IteratorPattern.MenuExample.MenuTestDriveOr for the Java built-in iterator example:
java -cp out IteratorPattern.MenuJavaUtilsExample.MenuTestDrive- Encapsulation: Hides the internal structure of the collection from the client
- Uniform Interface: Clients iterate over any collection type the same way
- Single Responsibility: Traversal logic is separated from the collection itself
- Open/Closed Principle: New collection types can be added without changing client code
Use the Iterator Pattern when:
- You want to access a collection's contents without knowing its internal structure
- You need to support multiple simultaneous traversals of a collection
- You want a uniform interface for traversing different collection types