|
| 1 | +# Iterator Pattern |
| 2 | + |
| 3 | +Provide a way to access the elements of an aggregate object / collection (e.g. trees, graphs and other complex data structures) sequentially without exposing its underlying representation. |
| 4 | + |
| 5 | +## Problem |
| 6 | + |
| 7 | +* The elements of an aggregate object should be accessed and traversed without exposing its representation (data structures). |
| 8 | + * Implementing the access and traversal operations directly in the aggregate interface is inflexible. |
| 9 | +* New traversal operations should be defined for an aggregate object without changing its interface. |
| 10 | + |
| 11 | +## Solution |
| 12 | + |
| 13 | +Define a separate `Iterator` object that encapsulates accessing and traversing an aggregate object |
| 14 | + |
| 15 | +## Common Structure |
| 16 | + |
| 17 | + |
| 18 | + |
| 19 | +* Iterator |
| 20 | + * defines an interface for accessing and traversing elements |
| 21 | +* ConcreteIterator |
| 22 | + * implements the Iterator interface |
| 23 | + * keeps track of the current position in the traversal of the aggregate. |
| 24 | +* Aggregate |
| 25 | + * defines an interface for creating an Iterator object |
| 26 | +* ConcreteAggregate |
| 27 | + * implements the Iterator creation interface to return an instance of the proper ConcreteIterator. |
| 28 | + |
| 29 | +## Collaboration |
| 30 | + |
| 31 | +* A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal. |
| 32 | + |
| 33 | +## Benefits |
| 34 | + |
| 35 | +* Simplifies the code of the aggregate object / collection. |
| 36 | +* Provide multiple ways to traverse the same data structure |
| 37 | + * Complex aggregates may be traversed in many ways (e.g. preorder, inorder or postorder traversal of trees) |
| 38 | +* Allows parallel traversing of the same collection |
| 39 | + |
| 40 | +## Drawbacks |
| 41 | + |
| 42 | +* Can be overkill for programs that work with simple collections. |
| 43 | + |
| 44 | +## Example |
| 45 | + |
| 46 | +**Definition** |
| 47 | + |
| 48 | +**Usage** |
| 49 | + |
| 50 | +## Comparison with other patterns |
| 51 | + |
| 52 | +* **Composite** - Iterators can be used for traversing Composite trees. |
| 53 | +* **Visitor** can be used along with Iterator pattern to traverse a complex data structure and execute some operation over all its elements even if they have different types. |
| 54 | +* **Memento** - can be used to capture current iteration state and roll it back if necessary. |
0 commit comments