迭代器模式(Iterator pattern)是比较常见的设计模式,它是一种行为模式,即使用一个迭代器遍历容器,并获取每一个元素。迭代器模式将遍历的算法和容器分离开来,使其能被重用,有些容器需要特定类型迭代器,也就不能重用。下面使用Java语言演示迭代器模式
interface Iterator{
Object nextItem();
Object currentItem();
boolean isEnd();
}
class SomeIterator implements Iterator{
private List<Object> list = new ArrayList<Object>();
private int cursor = 0;
public SomeIterator(List<Object> list){
this.list = list;
}
@Override
public Objec nextItem(){
cursor ++;
if(cursor >= list.size()){
return null;
}
return list.get(cursor);
}
@Override
public Object currentItem(){
if(cursor >= list.size()){
return null;
}
return list.get(cursor);
}
@Override
public boolean isEnd(){
return cursor >= list.size;
}
}
abstract class Container{
abstract Iterator createIterator();
}
class SomeContainer extends Container{
private List<Object> list = new ArrayList<Object>();
public SomeContainer(List<Object> list){
this.list = list;
}
public Iterator createIterator(){
return new ConcreteIterator(list);
}
}
class client{
public static void main(String[] args){
List<Object> list = new ArrayList<Object>();
list.add("objectOne");
list.add("objectTwo");
list.add("objectThree");
Container container = new SomeContainer(list);
Iterator iterator = container.createIterator();
while(!iterator.isEnd()){
System.out.println(iterator.currentItem());
iterator.nextItem();
}
}
}