模式动机
迭代器模式是为容器而生的,作为一个容器对象,肯定是需要对其进行遍历。你可以把遍历方法写到容器对象中去,也可以根本不提供遍历方法,让使用容器的人自己去实现。然而,第一种方式显然让容器类承担了太多的职责,第二种方式却会将容器的内部细节暴露出来。迭代器模式的出现,成功的解决了这类问题。它不仅提供了遍历容器对象的方法,同时不会暴露容器对象的内部细节,而且如果有需要还可以提供多种遍历方式。使用过java容器的人想必对Iterator接口并不陌生,它便是迭代器模式一个活生生的例子。
模式定义
提供一种方法来遍历容器对象,而不用暴露这个对象的内部表示,迭代器模式也叫游标模式。
模式结构
抽象迭代器:Iterator,定义访问和遍历元素的接口
具体迭代器:ConcreteIterator
抽象容器类:Aggregate,定义创建相应迭代器对象的接口,
具体容器类:ConcreteAggregate
代码示例
下面我们java中Collection是如何运用迭代器模式的
抽象迭代器,相当于类图中的Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
抽象容器类,以List为例,相当于类图中的Aggregate
public interface List<E> extends Collection<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
//其他方法不一一列举,有兴趣的可以查看jdk源码
}
具体容器类,如ArrayList类,相当于类图中的ConcreteAggregate,ArrayList实现了List接口,还继承了一个抽象类AbstractList,此抽象类把ArrayList等具体实现类的公共部分抽象了出来。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//源码省略……
}
具体迭代器类,相当于类图中的ConcreteIterator,这个角色是以内部类的形式存在的,它存在于AbstractList。源码篇幅较长,只贴出具体迭代器部分。
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//创建迭代器
public Iterator<E> iterator() {
return new Itr();
}
//下面是具体迭代器,提供了next、hasNext等方法
private class Itr implements Iterator<E> {
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
客户端使用时,容器对象只负责增加元素、删除元素等操作。访问、遍历等操作由迭代器负责。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("元素一");
list.add("元素二");
list.add("元素三");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
总结
迭代器模式的宗旨在于提供一种方法来访问容器对象,而不暴露此容器对象的内部结构,它把遍历容器对象等行为提取出来封装到一个专门的迭代器中。它适用于以下场景:访问一个聚合对象的内容而无须暴露它的内部表示;需要为聚合对象提供多种遍历方式;为遍历不同的聚合结构提供一个统一的接口。