理解名词
迭代器模式(Iterator Design Pattern)是一种行为型设计模式,也叫游标模式(Cursor Design Pattern)。
作用
用来遍历集合对象,将集合对象的遍历操作从集合类中拆分出来,放到迭代器类中,让两者的职责更加单一。
适用场景
当编程语言提供的迭代器类无法满足我们的需求时,例如我们有特定的元素遍历需求。或者自己开发了一个集合类,需要对外提供遍历器接口。
代码示例
首先实现一个迭代器接口,
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
接着实现一个遍历ArrayList的迭代器,
public class ArrayListIterator<E> implements Iterator<E> {
private int cursor;
private ArrayList<E> arrayList;
public boolean hasNext() {
return cursor < arrayList.size();
}
public E next() {
if (hasNext()) {
E e = arrayList.get(cursor);
++cursor;
return e;
}
return null;
}
// 非线程安全
public void remove() {
arrayList.remove(cursor);
}
}
List接口提供了一个获取迭代器的接口,容器类需要实现该接口。
public interface List {
Iterator iterator();
}
public class ArrayList implements List {
//...
public Iterator iterator() {
return new ArrayListIterator(this);
}
//...
}
使用示例
public class Demo {
public static void main(String[] args) {
List names = new ArrayList<>();
names.add("a");
names.add("b");
names.add("c");
names.add("d");
Iterator iterator = names.iterator();
iterator.next();
}
}
业界经典实现
- JDK ArrayList