Sunday, 6 November 2011

The Iterator Pattern

Intent:

Provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.

The simplest iterator has a "next element" method, which returns elements in some sequential order until there are no more. More sophisticated iterators might allow several directions and types of movement through a complex structure.

Typically an iterator has three tasks that might or might not be implemented in separate methods:
  • Testing whether elements are available
  • Advancing to the next n.th position
  • Accessing the value at the current position

Bidirectional iterators might have additional methods for checking and advancing the reverse direction.

Example

In the demonstration application, AppletPainter class uses Java ArrayList Iterator facility to iterate the Command objects in the CommandContainer class.

Class Diagram

No comments:

Post a Comment