Iterator (aka Cursor)

Intent

  • Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Problems

  • How can the elements of an aggregate object be accessed and traversed without exposing its underlying representation?

Solutions

  • Encapsulate the access and traversal of an aggregate in a separate Iterator object.

  • Clients request an Iterator object from an aggregate createIterator() and use it to access and traverse the aggregate.

Advantages

✅ Single Responsibility Principle: You can clean up the client code and the collections by extracting bulky traversal algorithms into separate classes. ✅ Open/Closed Principle: You can implement new types of collections and iterators and pass them to existing code without breaking anything. ✅ You can iterate over the same collection in parallel because each iterator object contains its own iteration state. ✅ For the same reason, you can delay an iteration and continue it when needed.

Disadvantages

❌ Applying the pattern can be an overkill if your app only works with simple collections. ❌ Using an iterator may be less efficient than going through elements of some specialized collections directly.

Last updated