The Iterator Design Pattern

Today I learned more about the Iterator Design Pattern and how it specifically applies to Java. The reason for choosing this topic is that during my project and talking with others the Iterator has come up a number of times throughout this semester. Now, I already knew about the Iterator in Java from taking Data Structures, but I never realized it was a design pattern before this course. The Iterator is actually a Gang of Four design pattern and it is classified as a behavioral pattern with object as the scope (GoF 257). The article gives a short summary of the iterator pattern and the reason it is used in Java. It is basically a way of accessing elements in a collection in order without having to know about the internal representation of the structure, a nice way of using abstraction. The author then gives a nice simple example in Java of how to use the Iterator pattern to access a collection of elements. He does this by creating a basic shape POJO with an id int and String name and stores them in another class that is an array of shapes. He then creates an Iterator class that defines the next element and if there is another element after the current one. This may be my favorite design pattern I’ve seen yet. It is simple to implement, but yet effective at its purpose, especially the way this article showed its implementation. I really like that once you’ve created an iterator for a type, all you need to do is pass in a collection of elements to it in order to process it. When I was working on the backend for my project I realized the need for something like an Iterator, especially with all the endpoints that were looping through the whole database. I wish I had implemented this so that I did not have to keep rewriting conditions to check that the data wasn’t out of bounds. In the future when I create my own programs with collections of elements I will make sure to implement an Iterator so that I can easily cycle through the data without having to worry about how to do it or constantly bounds checking the collection.

Source: https://www.javacodegeeks.com/2015/09/iterator-design-pattern.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s