Iterator - Harsh4999/Design-Patterns GitHub Wiki
Iterator
USE
- Whenever we have an aggregate object and we want to give access to its elements inside it in a sequential manner we use an iterator to iterate over it in order to access the internal members.
- Iterator helps us hide the internal data structure of aggregate objects internal data structures.
- Iterators are state full and if the underline collection changes while we are iterating the iterator becomes invalid. Sensitive to underline changes
UML
- Aggregate: gives out iterator reference by createiterator() method.
- Concrete Aggregate: implementation of aggregate
- Iterator: Is typically an interface which is used by client to iterate
- Concrete Iterator: Implementation of Iterator it defines methods like hasNext(), next() etc.
- Client: Makes aggregate and uses Iterator to iterate
Implementation
- Define Iterator interface provide hasNext(), next()
- Implement Iterator interface
- Concrete iterator needs to maintain some state
- Detecting changes to underlying collection is important to avoid errors.
- Having iterator as inner class helps access internal values.
- Eg: Collection framework Iterator