1. Pattern Intent
Alias cursors (Cursor), which provide a way to sequentially access elements of an aggregate object without exposing the object's internal objects.
The key idea of this pattern is to separate the access and traversal of the list/aggregation from the aggregate object and put it in an iterator object. The iterator class defines an interface that accesses the aggregate element. The iterator object is responsible for tracking the current element: that is, it knows which elements have been traversed.
Separating the traversal mechanism from the aggregate object allows us to define different iterators to implement different traversal strategies.
Iterators and aggregations are coupled, and the client object must know the aggregated structure of the traversal. There is a better way to change the aggregate class without changing the client code. This goal can be achieved by extending the concept of iterators to polymorphic iterations.
Create an iterator to have the aggregate object responsible for creating the appropriate iterator. The client requests that the operation be invoked to obtain an iterator object.
There can be multiple traversal on the same aggregation, and each iterator maintains its own traversal state. As a result, multiple traversal can be done at the same time.
2. Pattern definition
iterator (iterator): An iterator defines an interface that accesses and traverses elements.
specific iterator (concreteiterator): A specific iterator implements the iterator interface, and tracks the current position for the aggregation over time.
Aggregation (Aggregate): An aggregation defines an interface that creates an appropriate iterator object.
Concrete Aggregation (concreteaggregate): An interface for creating an appropriate iterator for a specific aggregation implementation.
3. Mode implementation 3.1 Java implementation iterator pattern
Interface Iterator {public Object next ();
public boolean hasnext ();
Class Concreteiterator implements iterator{private List = new ArrayList ();
private int cursor = 0;
Public concreteiterator (List list) {this.list = list;
public Boolean Hasnext () {if (Cursor==list.size ()) {return false;
return true;
Public Object Next () {object obj = null;
if (This.hasnext ()) {obj = This.list.get (cursor++);
return obj;
} interface Aggregate {public void Add (Object obj);
public void Remove (Object obj);
Public iterator iterator ();
Class Concreteaggregate implements Aggregate {Private list = new ArrayList ();
public void Add (Object obj) {list.add (obj);
Public iterator iterator () {return new concreteiterator (list); } public void Remove (Object obj) {list.remove (obj); } public class Client {public static void main (string[] args) {Aggregate ag = new Concreteaggregate
();
Ag.add ("1");
Ag.add ("2");
Ag.add ("3");
Iterator it = Ag.iterator ();
while (It.hasnext ()) {String str = (String) it.next ();
System.out.println (str); }
}
}
4. Pattern Application