The iterator behavioral pattern allows you to access objects in a collection or anything that contains multiple items without worrying about how this is done. The collection is sometimes referred to as an aggregate because it bundles multiple objects.

It works by defining an interface for your collection types to implement that defines a factory method to return an iterator. This iterator will actually be a concrete implementation of another interface for iterators. Your code will work with the collection interface in a uniform manner to create iterators of the correct type for the collection. then your code can work with the iterator also in a uniform manner through the iterator interface will will define methods such as first, next, current, and isDone.

The full sequence of methods you’ll need to call is:

  1. first to get things going.
  2. isDone to check if the aggregate even has items at all.
  3. current to get the actual first item in the aggregate.
  4. next to move to the next item.
  5. isDone needs to be called each time you move to the next item because there may not be a next item.
  6. Assuming we’re not yet done, call current to get the item and repeat the process by going back to step 4 and calling next again.

Also make sure to listen to episodes 45 and 46 where I explained the way iterators are implemented in the C++ Standard Library. I recommend that if you need to implement iterators in you classes, that you should follow the way C++ defines them with begin and end methods.