Java Reference
In-Depth Information
Iterator
Also known as Cursor
Pattern Properties
Type: Behavioral, Object
Level: Component
Purpose
To provide a consistent way to sequentially access items in a collection that is independent of and separate from
the underlying collection.
Introduction
The Personal Information Manager uses many collections, since it keeps track of large amounts of user data.
Addresses, contacts, projects, appointments, notes, to-do lists—all require the ability to store groups of related
objects.
To meet the storage needs of all these kinds of information, you might create classes to hold each group of items
used by the information manager. In this way, you could develop collections to meet the specific needs of each
group of objects.
This presents a problem, however, when you want to traverse each of the collections. If you create collection
classes that are specifically intended to meet the needs of the stored objects, there is no guarantee that the
elements will be retrieved and used in a uniform way. Appointments might be organized in subgroups according
to date, while contacts might be stored alphabetically, and notes might be sequentially ordered.
This means that you might have to write collection-specific code to move through items in each group, and copy
that code to any part of the system where you would need to use a group. Potentially, this could result in very
complicated, hard-to-maintain code. Furthermore, you need know in detail the different collection types used to
hold business objects of the PIM.
The Iterator pattern solves these problems by defining a uniform interface for traversing a collection—any
collection. When you use iterators in a system, you can use the same method calls when navigating through a list
of contacts as when you printed out a to-do list.
Applicability
Use the Iterator pattern:
To provide a uniform, consistent way to move through the elements in collections which is not tied to the
collection's implementation.
To allow multiple collection traversal, enabling several clients to simultaneously navigate within the same
underlying collection.
Description
At its foundation, the Iterator pattern allows you to standardize and simplify the code you write to move through
collections in your code. Collection classes tend to be created based on storage rather than traversal requirements.
The advantage of the Iterator pattern is that it provides a consistent way to handle navigation within collections
regardless of the underlying structure.
An Iterator in the Java programming language (“Java”) typically uses an interface to define its core operations,
then provides one or more implementations which link to the underlying aggregate. The Iterator described in
Design Patterns provides the following fundamental operations:
First
Next
 
Search WWH ::




Custom Search