1. Definition
The iterator mode provides a way to access each element in a container object without exposing the internal details of the object.
Basically, no one will write an iterator separately, unless it is a product development.
2. generic class diagram
Iterator abstract iterator: the abstract iterator defines interfaces for accessing and traversing elements, and basically has three fixed methods: First () to obtain the first element; next () access the next element; whether isdone () has accessed the bottom (Java is called the hasnext () method ).
Concreteiterator specific iterator: The specific iterator role must implement the iterator interface to traverse container elements.
Aggregate abstract container: The container role is responsible for providing interfaces for creating specific iterator roles. It must provide methods like createiterator (), which is generally the iterator () method in Java.
Concrete aggregate: a specific container defines the container interface and creates an object that can hold the iterator.
4. Common class code
Package iterator;/*** abstract iterator * 2:07:14-limiracle */public interface iterator {// traverse to the next element public object next (); // whether it has been traversed to the end of public Boolean hasnext (); // Delete the currently specified public Boolean remove ();}
Package iterator; import Java. util. vector;/*** specific iterator * 2:16:02-limiracle */public class concreteiterator implements iterator {private vector = new vector (); // define the current cursor public int cursor = 0; Public concreteiterator (vector) {This. vector = vector;} public object next () {object result = NULL; If (this. hasnext () {result = This. vector. get (this. cursor ++);} else {result = NULL;} return result;} // determines whether the public Boolean hasnext () {If (this. cursor = This. vector. size () {return false;} else {return true ;}// Delete the current element public Boolean remove () {This. vector. remove (this. cursor); Return true ;}}
Package iterator;/*** abstract container * 3:04:29-limiracle */public interface aggregate {// public void add (Object object) must be added to the container element ); // reduce the element public void remove (Object object); // The iterator traverses all elements public iterator ();}
Package iterator; import Java. util. vector;/*** specific container * 3:07:30-limiracle */public class concreteaggregate implements aggregate {// container containing the object private vector = new vector (); // Add an element public void add (Object object) {This. vector. add (object) ;}// return iterator object public iterator () {return New concreteiterator (this. vector);} // delete an element public void remove (Object object) {This. remove (object );}}