Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Use to traverse an aggregate without exposing internals, to support multiple simultaneous traversals, or to provide a uniform traversal interface across different aggregate structures.
Examples:
- A tree can be traversed depth-first, breadth-first, or randomly. Rather than baking each traversal algorithm into the Tree class — which blurs its responsibility — an Iterator object encapsulates the traversal logic; clients call next() without knowing whether the underlying structure is a list, a stack, or a graph.
class Iterator {
public:
virtual void First() = 0;
virtual void Next() = 0;
virtual bool IsDone() const = 0;
virtual Item CurrentItem() const = 0;
};
class ConcreteIterator : public Iterator {
ConcreteAggregate* agg;
int current = 0;
Item CurrentItem() const override { return agg->Get(current); }
};
Synonyms: cursor