一、基本介绍
迭代器模式也叫游标模式,是用来遍历集合对象的,这里的集合也叫容器,包含了一组对象,容器比如有:数组、链表、树等。
迭代器模式的作用是将集合对象的遍历操作从集合类中拆分出来,放到迭代器类中,让两者职责更加单一。
一个完整的迭代器模式应该涉及到容器和迭代器。容器包含容器接口、容器实现类;迭代器又包含迭代器接口、迭代器实现类。
迭代器模式
二、代码示例
- 迭代器接口
// 接口定义方式一
public interface Iterator<E> {
boolean hasNext();
void next();
E currentItem();
}
// 接口定义方式二
public interface Iterator<E> {
boolean hasNext();
E next(); //其实是合并了 后移一位和返回当前元素两个操作
}
- Array的迭代器实现
将对集合的操作解耦出来
public class ArrayIterator<E> implements Iterator<E> {
private int cursor;
private ArrayList<E> arrayList; //组合了Array集合
public ArrayIterator(ArrayList<E> arrayList) {
this.cursor = 0;
this.arrayList = arrayList;
}
@Override
public boolean hasNext() {
return cursor != arrayList.size(); //注意这里,cursor在指向最后一个元素的时候,hasNext()仍旧返回true。
}
@Override
public void next() {
cursor++;
}
@Override
public E currentItem() {
if (cursor >= arrayList.size()) {
throw new NoSuchElementException();
}
return arrayList.get(cursor);
}
}
- ArrayIterato的使用
public class Demo {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("xzg");
names.add("wang");
names.add("zheng");
Iterator<String> iterator = new ArrayIterator(names);
while (iterator.hasNext()) {
System.out.println(iterator.currentItem());
iterator.next();
}
}
}
三、优势
对复杂的数据结构进行遍历时使用迭代器模式可以拆分复杂的遍历方式,如图的深度优先遍历、广度优先遍历和树的前中后序遍历、层次遍历。