Iterator pattern
An Iterator is a design pattern used in software engineering. iterators allows access to the elements of an aggregate or collection data structure. Sometimes this pattern is also called cursor. Using the iterator, the elements of the data structure can be accessed sequentially, without exposing the implementation. Usually, iterators have methods to ask whether there is another item, and to get the next item. Depending on the implementation, they might also have methods for removing the current element or for finding the next element that meets certain criteria. In some implementations, iterators can only traverse data structures in one direction, while others allow traversal in both directions.
Iterators can be implemented in different ways:
- In the case of an external iterator, the client controls iteration, with an internal iterator, the iterator controls the iteration. External iterators have been called active, internal iterators have been called passive.
- In some cases, the way the data structure is traversed is dictated by the data structure, in other cases, it is the iterator that controls the traversal
- Iterators must be robust against changes of the data structure during iteration. Usually, iterators need to be registered with the data structure.
- In some implementations, iterators can take advantage of polymorphism.
- Combining the iterator with the pattern of null object creates an empty (or null) iterator