迭代器模式几乎在所有面向对象语言中都大量存在,且被很多语言支持,如java,c#等已经内部支持(也就是foreach)。迭代器模式可以为不同的集合对象提供统一的遍历接口,而不用关心集合的内部结构。遍历集合对象时,优先使用迭代器模式,能让代码更具可移植性和重用性。下面时具体代码(代码只是粗糙实现):
//声明一个集合接口
public interface Collection <E> {
public void add(E obj);
public void remove(E obj);
public int size();
public MyIterator<E> getIterator();
}
//声明一个迭代器接口
public interface MyIterator <E>{
public boolean hasNext();
public E next();
}
//实现Collection接口的具体集合类,内部维护了一个ArrayList对象,用于存放数据
public class MyCollection <E> implements Collection<E>{
private List<E> list = new ArrayList<E>();
@Override
public void add(E obj){
this.list.add(obj);
}
@Override
public void remove(E obj){
this.list.remove(obj);
}
@Override
public int size() {
return this.list.size();
}
//返回一个内部实现迭代器接口的具体迭代器
@Override
public MyIterator<E> getIterator(){
return new MyIteratorImpl();
}
private class MyIteratorImpl implements MyIterator<E>{
int current = -1;
//判断是否有下一节点
@Override
public boolean hasNext() {
if(current<size()-1){
return true;
}
return false;
}
@Override
public E next() {
current++;
return list.get(current);
}
}
}
//客户端类:
public class App {
public static void main(String[] args) {
Collection<Integer> collection = new MyCollection<Integer>();
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(4);
collection.add(5);
//返回一个实现MyIterator接口的对象。
//不同集合对象的遍历方式可能不同,提供统一的元素遍历接口,可以使代码的可移植性以及重用性提高很多s
MyIterator<Integer> iterator = collection.getIterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
运行输出发现,通过调用自定义的迭代器接口,collection中的全部数据都完整打印。
在java的util类库中,ArrayList和hashSet等集合都有自己实现的迭代器,但这些迭代器全部实现了一个Iterator接口,所以可以通过迭代器遍历不同集合
很多语言的foreach语法,其实经编译后都是调用迭代器接口的。由于时间关系,就不贴图了