迭代器模式有叫做游标(Cursor)模式。GOF给出的定义:提供一种方法访问一个容器(container)对象中的各个元素,而又不暴露该对象的内部细节。
迭代器模式由以下角色组成:
迭代器角色(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();
} |
|