Iterator Pattern

The Iterator Pattern provides a way to access the elements of an aggregates object sequentially without exposing its underlying representation.

Bates and SierraHead First Design Patterns

Class Diagram


Key Points

  • Encapsulate what varies. Iterator
    • knows how to iterate over a collection of item;
    • hides the collection implementation details;
    • depends on the collection and how to iterate over it.
  • Single Responsibility Principle.
    • A class should have only one reason to change.
    • Every responsibility of a class is an area of potential change.
  • Cohesion.
    • General concept related to Single Responsibility Principle.
    • Measure how closely a class or a module supports a single responsibility.
    • High cohesion: the class is designed around a set of related functions and is more maintainable.
    • Low cohesion: the class is design around a set of unrelated functions and is less maintainable.
  • Standard Interface. The Iterator is a well known interface and interact
    • in the same way with all the collections;
    • without knowing collection implementation details, decouples the client from the implementation details.
  • Other Interfaces. There are also
    • ListIterator allows to get also the previous item
    • Enumarate old interface
  • Polymorphic Iteration. The Iterator code iterate over any collection as long as it supports the interface.
  • for/in Statement to iterate over a collection without explicitly creating an iterator.