design patterns
Iterator
The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the traversal logic from the collection, allowing multiple traversals with different strategies. The key participants are the Iterator (defines an interface for accessing and traversing elements), ConcreteIterator (implements the Iterator interface and keeps track of the current position), Aggregate (defines an interface for creating an Iterator), and ConcreteAggregate (returns an instance of ConcreteIterator). Think of a TV remote with channel up/down buttons: you navigate through channels sequentially without knowing the internal channel list structure. Use Iterator when you need to access a collection's contents without exposing its internal representation, or when you want to support multiple simultaneous traversals.
Use Cases
- •Traversing custom data structures (trees, graphs, linked lists)
- •Paginated API results with lazy loading
- •Database result set cursors
- •File system directory traversal