Applied Design Patterns with Java

Behavioral :: Iterator (257) {C ch 19}


Example - Java :: Patterns\Behavioral\Iterator

Pattern Concept: to allow moving through a list or collection of objects using a standard interface, and without knowing the internal representation details of these objects. The Iterator pattern is useful because it provides a way to move through a set of elements without exposing the design of the element's classes. An Iterator is thus a logical navigation object.

An interface Iterator structure is used to operate on elements of type Object. Remember that all objects in Java ultimately derive from Object. Java 2 has such an interface Iterator already defined:

public interface Enumeration {

public boolean hasMoreElements();

public Object nextElement();

}

Here is a subset of the interface tree listing from the Java 2 help system:

This Enumeration type is used in Java 2 Vector and Hashtable classes; both contain a method that returns an enumeration:

public Enumeration elements();

Any instance of Vector, Hashtable, or any classes that derive from them, has this method available. The use of the Enumeration interface is the preferred way to build a Java Iterator. Java 2 also has an interface Iterator, which has the added feature of allowing the user to remove an element from a list.

Example - UML : KidEnumeration
Here is Cooper's Class Diagram for the application using this logic, followed by the Rose equivalent:





The example Java program is called 'KidEnumeration'.

The UML diagram is above, and the list of Java files is below:

Issues and consequences of the Iterator pattern include:

Catalog Behavioral Prev Next