Design Pattern Download: The Iterator Pattern

The Iterator pattern is a Behavioral Pattern used in software engineering when we want to separate our data structure logic from how the data structure is actually traversed.

Example

We have an array list type data we have multiple different “paths” for traversing the list. We could start from the end and finish at the first item, we could start at the beginning and wind up at the end, or we could do some weird quadratic probing traversal. However, we do not want to keep any of that logic in the actual data structure class instead we should extract it to some other class and separate functionality.

When to use the Iterator?

  • When we want to build different methods of traversing a data structure.

What is the Iterator composed of?

  • The Data structure( the underlying data structure we want to traverse)
  • The Iterators (the different classes which define how we traverse the data structure)

Implementation

The Data Structure

The Iterators

Now we can Iterate through the data structure and create new ways of iterating without the need to update the data structure itself.

0
1
2
3
4
5
6
7
8
9
9
8
7
6
5
4
3
2
1
0

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store