The iterator design pattern
We use iterators in software projects all the time. When we traverse a list or go through the items of a set or a map, we use an iterator.
Note
The iterator design pattern provides a way to access the elements of an aggregate object (collection) in a sequential manner without exposing the underlying representation of the items.
When using the iterator design pattern, the developer doesn't need to know whether there is a linked list, array, tree, or a hash map underneath.
Example class diagram
Using the iterator design pattern, we can create our own objects that act as collections and we can use them in loops. In Java, there is an interface called Iterator
, which we can implement for this purpose. In Scala, we can mix in the Iterator
trait and implement its hasNext
and next
methods.
For the class diagram and the example, let's have a ClassRoom class that will support a foreach loop running through all students. The following diagram shows our class diagram:

We've decided...