1.Topics‎ > ‎Architecture‎ > ‎Patterns‎ > ‎a.Design Patterns‎ > ‎D.Behavioral Patterns‎ > ‎

Iterator Pattern

  1. Summary
    1. It Allows access to the elements of any connection, in sequential manner, without exposing it`s underlying representation.
    2. The abstraction provided by the Iterator pattern allows you to modify the collection implementation without making any changes outside of collection. 
    3. It enables you to create a general purpose GUI component that will be able to iterate through any collection of the application.
  2. Overview Tutorials 
    1. http://www.oodesign.com/iterator-pattern.html
  3. Examples
    1. Dot.Net Collection Classes actually implement iterator pattern.
  4. Types
    1. External Iterator
      1. Iteration behavior is controlled by collection class. Languages like Java, C#, VB .NET, C++ is very easy to use external Iterator.
    2. Internal Iterator
      1. Iteration behavior is controlled by Iterator itself and languages like Smalltalk.
      2. Implementing and using internal iterators is really difficult. 
      3. When an internal iterator is used it means that the code is be run is delegated to the aggregate object.
    3. Robust Iterators
      1. An iterator that allows insertion and deletions without affecting the traversal and without making a copy of the aggregate is called a robust iterator. 
      2. A robust iterator will make sure that when elements are added or removed from an aggregate during iteration; elements are not accessed twice or ignored.
    4. Multithreading iterators
      1. First of all multithreading iterators should be robust iterators. 
      2. Second of all they should work in multithreading environments.
  5. Specific Considerations 
    1. Defining the traversal algorithm
      1. The algorithm for traversing the aggregate can be implemented in the iterator or in the aggregate itself.
      2. When the traversal algorithm is defined in the aggregate, the iterator is used only to store the state of the iterator. This kind of iterator is called a cursor because it points to the current position in the aggregate. 
      3. The other option is to implement the traversal algorithm in the iterator. This option offers certain advantages and some disadvantages. For example it is easier to implement different algorithms to reuse the same iterators on different aggregates and to subclass the iterator in order to change its behavior. The main disadvantage is that the iterator will have to access internal members of the aggregate. In Java and .NET this can be done, without violating the encapsulation principle, by making the iterator an inner class of the aggregate class.
    2. Iterator and Cursor
      1. When the traversal algorithm is defined in the aggregate, then it is called a cursor because it points to the current position in the aggregate.