Design Pattern Tour: Behavioral Patterns
Iterator
Readings:
Iterator is an approach to provide collections(or containers) a common way to traverse, while hiding the inner structure of the collections. The application of it is obvious: Java and CPP both use this pattern.
For the structure of this pattern, the collection class normally provides an interface of getIterator()
, the iterator class, on the other hand, offers interfaces of hasNext()
and getNext()
. In the concrete iterator class, we usually need to add a variable as a reference to the collection instance.
Concrete iterators can implement different kinds of traversal methods(e.x. DFS, BFS, etc.) easily, which makes it quite convenient to add new collections and iterators, or to replace current collections and iterators with new one in the client code. This design is not only good for extensibility but also Open/Closed Principle.
The separation of collections and iterators decouples the traversal from business logics, embodying Single Responsibility Principle. However, it sometimes might make things more complicated.