You can follow along with my github repo where I implement each design pattern individually. Looking at the code can help you internalize the material so I do encourage you to follow the repo for updates as I continue to develop this course: Design Patterns Repo
The Iterator Pattern is a behavioural design pattern that provides a way to access the elements of a collection object sequentially without exposing its underlying representation. It decouples the logic of traversing a data structure from the structure itself, making it easier to work with collections in a consistent way.
By using an iterator, developers can traverse lists, trees, sets, and other data structures without needing to know the internal workings of these structures. This promotes encapsulation and simplifies code that processes collections.
Pattern Structure
The core structure involves:
- Iterator: Defines the interface for accessing and traversing elements
- Concrete Iterator: Implements the iterator interface and keeps track of the current position
- Aggregate: Provides an interface for creating an iterator object
- Concrete Aggregate: Implements the aggregate interface and returns a specific iterator instance
Real-World Analogy
Imagine reading a book:
- You flip pages one at a time using a bookmark (iterator).
- The book's internal structure (its binding, paper, page numbering) is irrelevant.
- What matters is that you can move forward or backward using a simple tool
Similarly, an iterator acts as a bookmark for a collection, letting you move through the contents without revealing how they're stored or linked internally.
Software Use Case
In software development, the iterator is widely used in libraries and frameworks:
- The Java Collections Frameworks uses 'iterator' for list, set, and map traversal.
- Python uses '__iter__' and '__next__' for native iteration over containers.
For example, a file browser may use an iterator to traverse files in a directory, abstracting the underlying file system traversal logic. Developers can loop over the files without worrying whether they';re stored in memory, fetched over a network, or dynamically generated.
UML Components
Benefits
- Uniform traversal interface: Works across different data structures
- Encapsulation: Collection's internals remain hidden
- Multiple traversal algorithms: You can implement different iterators for the same collection
Trade-Offs
- Extra complexity: May introduce additional classes and interfaces
- Performance overhead: Iterators may require additional state to track positions
Best Practices
- Use when multiple or flexible traversals are required
- Combine with Composite or Aggregate patterns for hierarchical data structures
- Provide both multiple and immutable iterators for advanced use cases
Final Thoughts
Article by


