• Albert Bennett

Design Patterns: Iterator

Updated: Jul 12, 2021

Here is the link to the GitHub repo :)

Feel free to like, comment and share this post.


In this post I'll be going through the Iterator pattern. What it's used for and how does it work.


For this design pattern the name says it all really. It's used to iterate through objects without exposing the underlying collection, in short it's like a fancy foreach loop without the exposure. Here is a diagram to better explain how it's structured:


Now for our use case. We want to iterate through all of the cars in our car park, and write out the type of each car.


First up we have to define our car. This is the object that our Aggregate is going to be storing and that we will be iterating through.


Aggregate: This holds a collection of objects (cars) that our iterator will be... iterating through. For our sample I'll be using T as the type parameter. This is to make our code more reusable.



Iterator: This is what is going to be doing the actual iteration through the collection of cars.



Now for the actual implementation of our design pattern.



As you can see, from the image. The program cycles through the collection without exposing it. Neat!

Well... I hope that helps you to understand the Iterator pattern. See you next time (⌐■_■)


<< More Design Patterns

13 views0 comments

Recent Posts

See All