Java Reference
In-Depth Information
IsDone
CurrentItem
These operations define the basic services that an Iterator must provide in order to do its job. In more general
terms, an Iterator should provide the following core capabilities:
Navigation - Moving forward or backward within the collection
Retrieval - Getting the currently referenced element
Validation - Determining if there are still elements in the collection, based on the Iterator's current position
Iterators may also provide extended operations. Some Iterators provide methods to move to the first or last
element in the Iterator, for example.
Implementation
The Iterator class diagram is shown in Figure 2.7 .
Figure 2.7. Iterator class diagram
To implement the Iterator pattern, you need:
Iterator - This interface defines the standard iteration methods. At a minimum, the interface defines methods
for navigation, retrieval and validation ( first , next , hasMoreElements and getCurrentItem )
ConcreteIterator - Classes that implement the Iterator . These classes reference the underlying collection.
Normally, instances are created by the ConcreteAggregate . Because of the tight coupling with the
ConcreteAggregate , the ConcreteIterator often is an inner class of the ConcreteAggregate .
Aggregate - This interface defines a factory method to produce the Iterator .
ConcreteAggregate - This class implements the Aggregate , building a ConcreteIterator on demand. The
ConcreteAggregate performs this task in addition to its fundamental responsibility of representing a collection
of objects in a system. ConcreteAggregate creates the ConcreteIterator instance.
Benefits and Drawbacks
Many of the Iterator pattern's benefits stem from the advantages of defining a uniform interface for collection
traversal. This greatly simplifies the use of collections, and allows you to use polymorphism when working with
collections. To print the elements in any collection, for instance, you could obtain an Iterator , then call the
toString method on any object, regardless of its underlying collection.
 
Search WWH ::




Custom Search