Iterator Design Pattern

Iterator design pattern image


Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. (dofactory)

  • Iterator defines an interface for accessing and traversing elements.
  • ConcreteIterator implements the Iterator interface and keeps track of the current position in the traversal of the aggregate.
  • Aggregate defines an interface for creating an Iterator object
  • ConcreteAggregate implements the Iterator creation interface to return an instance of the proper ConcreteIterator

  • When the iteration is controlled by the aggregate object we say that we have an external Iterator (In languages like .net on java it's very easy to create external iterators)  and when the iterator controls it we have an internal iterator;The main idea is to pass the code to be executed to the collection (In C++ it's possible to send the doMethod method as a pointer. In C# .NET or VB.NET it is possible to send the method as a delegate. In java the Functor design pattern has to be used. The main idea is to create a base Interface with only one method (doSomething). Then the method will be implemented in a class which implements the interface and the class will be passed to the collection to iterate.). 
  • The iterator pattern can be implemented from scratch in Java or .NET, but there is already built-in support for Iterator Pattern (IEnumerator/IEnumerable in .NET and Iterator/Collection in JAVA).
  • An iterator that allows insertion and deletions without affecting the traversal and without making a copy of the aggregate is called a robust iterator. 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.

  • Access contents of a collection without exposing its internal structure.
  • Support multiple simultaneous traversals of a collection.
  • Provide a uniform interface for traversing different collection.

  • Access to elements in a set without access to the entire representation.
  • A uniform traversal interface, and multiple traversals may happen across elements

  • I don't see any disadvantages to this pattern. However, this pattern give the illusion of order to unordered structures and If you don’t realize this, you could write code that assumed consistency in the underlying structure, which would result in problems later on

Sample Code
Classic Iterator pattern example

Iterator pattern using IEnumerator example

Related Patterns
  • Iterator can traverse a Composite. Visitor can apply an operation over a Composite.
  • Polymorphic Iterators rely on Factory Methods to instantiate the appropriate Iterator subclass.
  • Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.



Popular Posts