Iterator

Structural pattern

This design pattern allows us to go over a data structure without needing to know its internal construction. It is especially useful when we are working with complex data structures, because it lets us go over their elements through an iterator. The iterator is an interface including the necessary methods for reviewing all the elements of a data structure. The most common methods are:

  • hasNext: This method returns a Boolean indicating if there are more elements to be reviewed in the structure. It returns true if there still are elements left and false if there are none left.
  • next: It returns the next element in the data structure.
Iterator design pattern structure.
Iterator design pattern structure.

The Iterator pattern elements are:

  • Client: Actor using the iterator.
  • Aggregate: Interface defining the class structures that can be iterated.
  • ConcreteAggregate: Class containing the data structure we want to iterate.
  • IIterator: Interface defining the iterator's structure, including the necessary methods for performing the iteration over ConcreteAggregator.
  • ConcreteIterator: It represents an iterator's concrete implementation, which will be in charge of iterating the ConcreteAggregate data.
Iterator pattern sequence diagram
Iterator pattern sequence diagram
  • The client sends a request for an iterator to ConcreteAggregate .
  • ConcreteAggregate creates a new Iterator.
  • The cliententers in a loop in order to review all the elements on the structure, the loop ends when there are no elements left for reviewing, which is going to be signaled by the hasNext method.
  • The client sends the request for a new element to the iterator using the nextmethod.
  • If there are elements left to be reviewed, then we return to step 3, something that is going to be repeated until all elements have been reviewed.

Real-world example

By implementing the Iterator design pattern, we are going to create an application that allows us to traverse a hierarchical organizational structure, by including an iterator, which will go over the entire tree sequentially.

Discover how the Iterator pattern can help us solve this problem
Discover how the Iterator pattern can help us solve this problem

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.