Thursday, March 31, 2022

SKP's GoF Design Patterns a Day - 07 - Iterator

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 

Iterator Pattern [Sample Code]
The need to have a handle to a collection of elements, without exposing its internal implementation is met by the Iterator Pattern. I would term this as a pure programming pattern, in its own right. By utilising this handle (Iterator), the client using the collection can easily process the same without any dependency on the internal logic.
 
Fig. 5 : Iterator (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


In the attached example, ProductMenu holds a menu or list of ProductItem. This list and its usage should be implementation agnostic to the clients. Hence, the need for a ProductIterator which implements the generic Iterator interface. The createIterator() method of ProductMenu, passes the array implementation of ProductItem to the constructor of ProductIterator.

The example can be run using ProductMenuTester.

No comments: