The iterator (iterator) pattern, also known as the cursor (Cursor) pattern. GOF is defined as providing a way to access the elements of a container (container) object without exposing the internal details of the object.
The iterator pattern consists of the following roles:
iterator Role (iterator): The iterator role is responsible for defining interfaces that access and traverse elements.
Specific iterator role (concrete iterator): The specific iterator role implements the iterator interface and records the current position in the traversal.
Container Role (Container): The container role is responsible for providing an interface to create a specific iterator role.
The specific container role (concrete Container): The container role implements the interface that creates the specific iterator role. This specific iterator role is associated with the structure of the container.
Java Implementation Example
class Diagram:
Code:
/**
* Custom Collection interface, similar to java.util.Collection
* for data storage
* @author Stone
*
* * Public
interface icollection<t> {
iiterator<t> iterator ();//return iterator
void Add (t);
T get (int index);
}
/** * Custom iterator interface is similar to Java.util.Iterator * data used to traverse collection class ICollection * @author Stone *
* * Public interface Iiterator<t> {Boolean hasnext ();
Boolean hasprevious ();
T next ();
T Previous (); }
/**
* Collection class, dependent on Myiterator
* @author Stone * * Public
class Mycollection<t> implements ICollection <T> {
private t[] Arys;
private int index =-1;
private int capacity = 5;
Public mycollection () {
This.arys = (t[]) new object[capacity];
@Override Public
iiterator<t> iterator () {return to
new myiterator<t> (this);
}
@Override public
void Add (t) {
index++;
if (index = = capacity) {
capacity *= 2;
This.arys = arrays.copyof (Arys, capacity);
}
This.arys[index] = t;
}
@Override public
T get (int index) {return
this.arys[index];
}
}
* * If there is a new storage structure, can be a ICollection, the corresponding new one iiterator to achieve its traversal
/@SuppressWarnings ({"Rawtypes", " Unchecked "}" public
class Test {public
static void Main (string[] args) {
icollection<integer> Collection = new Mycollection<integer> ();
Add (Collection, 3, 5, 8, 3, 3, 5);
for (iiterator<integer> iterator = Collection.iterator (); Iterator.hasnext ();) {
System.out.println (Iterator.next ());
}
System.out.println ("-------------");
ICollection Collection2 = new mycollection ();
Add (Collection2, "a", "B", "C", 3, 8, 3, 5);
for (Iiterator iterator = Collection2.iterator (); Iterator.hasnext ();) {
System.out.println (Iterator.next ());
}
}
static <T> void Add (icollection<t> C, T.. a) {for
(t i:a) {
c.add (i)}
}}
Print:
3
5
8
3
3 5
-------------
a
b
c
3
8
3
5