Overview
Given a language, it defines a representation of its syntax and an interpreter that uses this representation to interpret sentences in the language.
Applicability
1. Access the content of an aggregate object without exposing its internal representation.
2. Supports multiple traversal of aggregate objects.
3. provides a unified interface (supporting multi-state iteration) for Traversing different aggregation structures ).
Participants
1. Iterator
The iterator defines interfaces for accessing and traversing elements.
2. ConcreteIterator
The specific iterator implements the iterator interface.
Tracks the current position of the aggregated time.
3. Aggregate
Aggregate defines the interface for creating the corresponding iterator object.
4. ConcreteAggregate
The specific aggregation implementation creates an interface for the corresponding iterator. This operation returns an appropriate instance of ConcreteIterator.
Class Diagram
Sample Code:
Package com. sql9.actioned;
Import java. util. ArrayList;
Import java. util. List;
/**
* Implementation example of the iterator Mode
* @ Author sean
*/
Interface IIterator <T> {
T next ();
Void first ();
Void last ();
Boolean hasNext ();
}
Class IIteratorImpl <T> implements IIterator <T> {
Private IList <T> list;
Private int index;
Public IIteratorImpl (IList <T> list ){
Index = 0;
This. list = list;
}
@ Override
Public T next (){
T t = list. get (index );
Index ++;
Return t;
}
@ Override
Public void first (){
Index = 0;
}
@ Override
Public void last (){
Index = list. size ();
}
@ Override
Public boolean hasNext (){
Return index <list. size ();
}
}
Interface IList <T> {
IIterator <T> iterator ();
T get (int index );
Int size ();
Void add (T obj );
}
Class IListImpl <T> implements IList <T> {
Private List <T> list;
Private int index;
Public IListImpl (){
List = new ArrayList <T> ();
Index = 0;
}
@ Override
Public IIterator <T> iterator (){
Return new IIteratorImpl <T> (this );
}
@ Override
Public T get (int index ){
Return list. get (index );
}
@ Override
Public int size (){
Return list. size ();
}
@ Override
Public void add (T obj ){
List. add (obj );
}
}
Public class IteratorTest {
Public static void main (String [] args ){
// 2 ways of iteration
IList <String> list = new IListImpl <String> ();
List. add ("");
List. add ("B ");
List. add ("c ");
// 1st way www.2cto.com
System. out. println ("1. using iterator to traverse :");
IIterator <String> iter = list. iterator ();
While (iter. hasNext ()){
System. out. println (iter. next ());
}
// 2nd way
System. out. println ("2. using list to traverse :");
For (int I = 0; I <list. size (); I ++ ){
System. out. println (list. get (I ));
}
}
}
Result:
1. using iterator to traverse:
A
B
C
2. using list to traverse:
A
B
C