Skip to content

Latest commit

 

History

History
71 lines (44 loc) · 2.49 KB

File metadata and controls

71 lines (44 loc) · 2.49 KB

Iterator Pattern

Overview

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Pattern Structure

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.

Key Concepts

  • Iterator: Interface defining hasNext() and next() 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

Examples

MenuExample

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.

MenuJavaUtilsExample

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.

How to Compile

From the project root:

javac -d out IteratorPattern/MenuExample/*.java

Or for the Java built-in iterator example:

javac -d out IteratorPattern/MenuJavaUtilsExample/*.java

How to Run

java -cp out IteratorPattern.MenuExample.MenuTestDrive

Or for the Java built-in iterator example:

java -cp out IteratorPattern.MenuJavaUtilsExample.MenuTestDrive

Benefits of the Iterator Pattern

  • 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

When to Use

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