Java 迭代器模式
迭代器模式由以下角色組成:
迭代器角色(Iterator): 負責定義訪問和遍歷元素的介面。
具體迭代器角色(Concrete Iterator):實現迭代器介面,並要記錄遍歷中的當前位置。
容器角色(Container): 負責提供建立具體迭代器角色的介面。
具體容器角色(Concrete Container):實現建立具體迭代器角色的介面, 這個具體迭代器角色與該容器的結構相關。
類圖:
例項:
public interface Iterator
{
public Object first();
public Object next();
public Object currentItem();
public boolean isDone();
}
public class ConcreteIterator implements Iterator
{
private int currentIndex = 0;
private Vector vector = null;
public ConcreteIterator(final Vector vector)
{
this.vector = vector;
}
@Override
public Object first()
{
currentIndex = 0;
return vector.get(currentIndex);
}
@Override
public Object next()
{
currentIndex++;
return vector.get(currentIndex);
}
@Override
public Object currentItem()
{
return vector.get(currentIndex);
}
@Override
public boolean isDone()
{
if (currentIndex >= this.vector.size() - 1)
{
return true;
}
else
{
return false;
}
}
}
public interface Aggregat
{
public Iterator createIterator();
}
public class ConcreteAggregat implements Aggregat
{
private Vector vector = null;
public Vector getVector()
{
return vector;
}
public void setVector(final Vector vector)
{
this.vector = vector;
}
public ConcreteAggregat()
{
vector = new Vector();
vector.add("vector 1");
vector.add("vector 2");
}
@Override
public Iterator createIterator()
{
return new ConcreteIterator(vector);
}
}
public class Client
{
public static void main(final String[] args)
{
final Aggregat agg = new ConcreteAggregat();
final Iterator iterator = agg.createIterator();
System.out.println(iterator.first());
while (!iterator.isDone())
{
System.out.println(iterator.next());
}
}
}
結果:
vector 1
vector 2
JDK也提供了迭代介面進行java collection的遍歷:
Iterator it = list.iterator();while(it.hasNext()){
//using it.next();
}