iterator design pattern very high level concept pictorial explanation.

Iterator pattern is all about streamline the access of the collection so that the client which want to iterate over collection must not worry about entire collection instead it just check if list hasNext() element and call next() element.

It’s a type of behavioral design pattern which is also known as cursor.

Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. — GOF book definition.

Simple Example

Consider you have two apparel stores MensApparelStore and WomensApparelStore both decided to merge their business and start a new store name as MensAndWomensApparelStore.
Both owners finds this as a good idea but problem was with their catalog structure. Both of them had a method which returns a catalog but MensApparelStore has ArrayList getCatalog() and WomensApparelStore has Array getCatalog() .
Both of them returns a different return type, but they wish to merge a their catalog.

Solution
This can be achieve just by iterating using for loop over both the catalog list in MensAndWomensApparelStore but there is an efficient way to do it which is using the iterator pattern. (please refer below UML diagram).
By implementing iterator pattern we can achieve three things,
1) make return type adaptable to the client class
2) use the same iterator logic (for loop) to iterate both lists.
3) not exposing an entire list of products instead pass each element when needed.

solution design UML diagram

Please refer to a GitHub code for both without an iterator pattern and with an iterator pattern code example . (github code link for above iterator pattern example).

Before I learned this pattern I was under impression that what iterator pattern does the same can be done with a simple for loop which is true but when I understood the core intent behind why this is introduced? and what problem it solved? I understood that for loop and iterator are supporting each other when the entire collection is not expected to expose or when the collection which the client wants to iterate is complex then using iterator is good choice.

The real fun is in the details, if you wish to know and understand the pros-cons, java-code example for the iterator pattern then please consider checking the detailed article at [iterator-pattern-explained-7-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

On the journey to understand the core essence of design patterns.
Every Tuesday I publish a small 2 min post and a long 5–10 min post along with a code example, please consider following if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT