/Design Patterns /Behavioral patterns

Iterator Design Pattern

Intent

  • Provide a way to access the elements of an aggregate objectsequentially without exposing its underlying representation.
  • The C++ and Java standard library abstraction that makes it possibleto decouple collection classes and algorithms.
  • Promote to "full object status" the traversal of a collection.
  • Polymorphic traversal

Problem

Need to "abstract" the traversal of wildly different data structuresso that algorithms can be defined that are capable of interfacing witheach transparently.

Discussion

"An aggregate object such as a list should give you a way to accessits elements without exposing its internal structure. Moreover, youmight want to traverse the list in different ways, depending on whatyou need to accomplish. But you probably don't want to bloat the Listinterface with operations for different traversals, even if youcould anticipate the ones you'll require. You might also need to havemore than one traversal pending on the same list." And,providing a uniform interface for traversing many types of aggregateobjects (i.e. polymorphic iteration) might be valuable.

The Iterator pattern lets you do all this. The key idea is to take theresponsibility for access and traversal out of the aggregate objectand put it into an Iterator object that defines a standard traversalprotocol.

The Iterator abstraction is fundamental to an emerging technologycalled "generic programming". This strategy seeks to explicitlyseparate the notion of "algorithm" from that of "data structure". Themotivation is to: promote component-based development, boostproductivity, and reduce configuration management.

As an example, if you wanted to support four data structures (array,binary tree, linked list, and hash table) and three algorithms (sort,find, and merge), a traditional approach would require four times threepermutations to develop and maintain. Whereas, a generic programmingapproach would only require four plus three configuration items.

Structure

The Client uses the Collection class' public interface directly. Butaccess to the Collection's elements is encapsulated behind theadditional level of abstraction called Iterator. Each Collectionderived class knows which Iterator derived class to create and return.After that, the Client relies on the interface defined in the Iteratorbase class.

Iterator example

Example

The Iterator provides ways to access elements of an aggregate objectsequentially without exposing the underlying structure of the object.Files are aggregate objects. In office settings where access to filesis made through administrative or secretarial staff, the Iteratorpattern is demonstrated with the secretary acting as the Iterator.Several television comedy skits have been developed around the premiseof an executive trying to understand the secretary's filing system. Tothe executive, the filing system is confusing and illogical, but thesecretary is able to access files quickly and efficiently.

On early television sets, a dial was used to change channels. Whenchannel surfing, the viewer was required to move the dial through eachchannel position, regardless of whether or not that channel had reception.On modern television sets, a next and previous button are used. When theviewer selects the "next" button, the next tuned channel will be displayed.Consider watching television in a hotel room in a strange city. Whensurfing through channels, the channel number is not important, but theprogramming is. If the programming on one channel is not of interest, theviewer can request the next channel, without knowing its number.

Iterator example

Check list

  1. Add acreate_iterator() method to the "collection" class,and grant the "iterator" class privileged access.
  2. Design an "iterator" class that can encapsulate traversal of the"collection" class.
  3. Clients ask the collection object to create an iterator object.
  4. Clients use thefirst(),is_done(),next(), andcurrent_item() protocol to accessthe elements of the collection class.

Rules of thumb

  • The abstract syntax tree of Interpreter is a Composite (thereforeIterator and Visitor are also applicable).
  • Iterator can traverse a Composite. Visitor can apply an operation overa Composite.
  • Polymorphic Iterators rely on Factory Methods to instantiate theappropriate Iterator subclass.
  • Memento is often used in conjunction with Iterator. An Iterator can usea Memento to capture the state of an iteration. The Iterator stores theMemento internally.

Support our free website and own the eBook!

  • 22 design patterns and 8 principles explained in depth
  • 406 well-structured, easy to read, jargon-free pages
  • 228 clear and helpful illustrations and diagrams
  • An archive with code examples in 4 languages
  • All devices supported: EPUB/MOBI/PDF formats
Learn more...

Code examples

Hey, check out our newebook on design patterns. The book covers 22 patterns and 8 design principles, all supplied with code examples and illustrations. Clear, short and fun!

Oh, and it is on saleright now.