《迭代器模式》|设计模式系列第16篇
系列:行为型模式 · 迭代器模式(Iterator Pattern)
关键词:遍历集合、统一访问、隐藏内部结构、迭代器、聚合
一、什么是迭代器模式
迭代器模式(Iterator Pattern):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
属于行为型设计模式。

简单理解:
迭代器就是专门用来遍历集合的工具。聚合对象(容器)内部的数据结构可以是数组、List、链表等,迭代器对外提供统一的遍历接口,客户端不需要关心底层存储结构,只需要通过迭代器依次获取元素。Java集合里的Iterator就是迭代器模式的典型实现。
核心意图
隔离集合内部实现,提供统一遍历方式;让客户端无需了解容器底层结构即可遍历元素。
适用场景
- 需要为多种不同聚合结构提供统一遍历接口
- 不想暴露聚合对象内部存储细节
- 希望提供多种遍历方式(正向、反向、过滤遍历)
- 统一不同容器的遍历API
⚠️ 缺点预警:简单场景下会增加额外类;对于已经提供迭代器的原生集合,没必要重复实现。
二、UML结构图
角色划分:
- Aggregate(抽象聚合):声明创建迭代器的方法
- ConcreteAggregate(具体聚合):实现创建迭代器方法,保存元素集合
- Iterator(抽象迭代器):定义遍历接口,hasNext()、next()
- ConcreteIterator(具体迭代器):实现迭代器接口,维护遍历游标
- Client(客户端):使用迭代器遍历聚合对象,不直接访问内部元素

三、Java 完整示例
场景:CustomCollection 自定义集合,存放 string 元素,自定义迭代器遍历。
代码全部使用英文。
1. Iterator 抽象迭代器
public interface Iterator<T> {
boolean hasNext();
T next();
}
2. Aggregate 抽象聚合
public interface Aggregate<T> {
Iterator<T> createIterator();
}
3. ConcreteAggregate 具体聚合
public class CustomCollection<T> implements Aggregate<T> {
private T[] items;
private int index = 0;
public CustomCollection(int capacity) {
items = (T[]) new Object[capacity];
}
public void add(T item) {
if(index < items.length){
items[index++] = item;
}
}
public T get(int idx) {
return items[idx];
}
public int getSize() {
return index;
}
@Override
public Iterator<T> createIterator() {
return new CustomIterator(this);
}
}
4. ConcreteIterator 具体迭代器
public class CustomIterator<T> implements Iterator<T> {
private CustomCollection<T> collection;
private int cursor;
public CustomIterator(CustomCollection<T> collection) {
this.collection = collection;
this.cursor = 0;
}
@Override
public boolean hasNext() {
return cursor < collection.getSize();
}
@Override
public T next() {
return collection.get(cursor++);
}
}
5. Client 客户端
public class Client {
public static void main(String[] args) {
CustomCollection<String> collection = new CustomCollection<>(5);
collection.add("A");
collection.add("B");
collection.add("C");
Iterator<String> iterator = collection.createIterator();
while(iterator.hasNext()){
String item = iterator.next();
System.out.println(item);
}
}
}
运行输出:
A
B
C
四、优缺点总结
✅ 优点
- 统一遍历接口,客户端无需关心容器底层存储
- 遍历逻辑和容器存储逻辑分离,单一职责
- 同一个聚合对象,可以创建多个独立迭代器,游标互不干扰
- 可灵活扩展多种遍历方式(反向迭代、过滤迭代)
❌ 缺点
- 简单容器场景,额外增加迭代器类,代码冗余
- 遍历过程中修改集合元素,容易触发并发修改异常
五、框架源码应用
- JDK
java.util.Iterator、java.util.ListIterator - MyBatis
ResultIterator - Spring
CompositeIterator
六、小结
迭代器模式核心:将遍历逻辑抽离到迭代器对象,隐藏聚合对象内部结构,提供统一元素访问方式。
日常开发大多直接使用JDK内置Iterator,很少手写迭代器;理解其思想,当需要自定义特殊容器遍历逻辑时使用。
0 条笔记