The Iterator Pattern
The iterator pattern is a design pattern which can be used to decouple (traversal) algorithms from containers.
We’ll take a look into what it actually is, how to apply it, and which problems it solves!
What does it state?
1. The elements of an aggregate object should be accessed and traversed without exposing its representation (underlying data structure)
2. New traversal operations should be defined for an aggregate object without changing its interface
Those two points may sound a little complicated, but you can view it this way:
If you define access and traversal operations within an object’s interface (its methods, viewable and usable from the outside), it becomes inflexible.
You simply can’t change the interface without breaking some code, especially code which implements the interface.
This applies to all code. The one you’ve written, and the one others have written, third-parties so to say. But if you provide a common interface, which all containers and users can agree on, you can decouple access and traversal logic completely, and let your container only return one common interface.