Iterator#
The Iterator pattern is a behavioral design pattern that allows you to traverse elements of a collection (like a list or a set) without exposing the underlying representation. It provides a way to access the elements of an aggregate object sequentially without exposing its underlying structure.
In simpler terms, it allows you to loop through a collection of objects in a standard way without needing to know the details of how the collection is implemented.
Common use cases#
Collections: Traversing elements in collections like lists, sets, or maps without exposing their internal structure.
Tree Structures: Navigating through tree structures, such as DOM trees in web development.
Custom Data Structures: Iterating over custom data structures where a standard iteration mechanism is not available.
File Systems: Iterating over files and directories in a file system.
Database Results: Traversing through rows in a database result set.
Aggregated Data: Iterating over aggregated data from multiple sources.
Streaming Data: Processing elements in a stream of data, such as log files or network packets.
UML Diagram#
+-------------------+ +-------------------+
| Aggregate | | Iterator |
+-------------------+ +-------------------+
| +createIterator() |<>----| +next() |
+-------------------+ | +hasNext() |
+-------------------+
^
|
|
+-------------------+
| ConcreteIterator |
+-------------------+
| -currentPosition |
+-------------------+
| +next() |
| +hasNext() |
+-------------------+
^
|
|
+-------------------+
| ConcreteAggregate |
+-------------------+
| -items |
+-------------------+
| +createIterator() |
+-------------------+
--- Python Example ---