Iterator Pattern
The Iterator pattern: walking a collection one element at a time without knowing how it is stored, and why a Python generator can be walked only once.
A list, a tree, and a set of results fetched a page at a time from a server are stored in three different ways, yet a loop can read each of them one item at a time. The Iterator pattern makes that possible: the collection hands out a separate object that keeps the position and returns the next item, and the loop talks only to that object.
This topic opens on a caller tied to a collection's internals, then reads the participants off the class diagram, and shows why the position lives outside the collection. The template implements each language's own iterator protocol: __iter__ and __next__ in Python, Iterable and Iterator in Java, and Symbol.iterator in TypeScript.
Two examples follow: an iterator that fetches the next page of orders only when the current page runs out, and TypeScript's for...of, spread and destructuring, which all rely on the same protocol. A comparison shows the generator, the usual Python form, which keeps the position for you. The gotcha is a generator that is empty the second time it is walked, and the exercise writes an iterator over a binary tree that can be walked twice.
By the end you can recognise an iterator, write one in each language, and predict when one has been used up.
Contents
9 cardsnot started