1. 模式精髓:解耦遍历与集合
迭代器模式(Iterator Pattern)的核心思想在于:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。这种设计带来两个关键优势:
- 简化了聚合对象的接口
- 将遍历责任分离,符合单一职责原则
2. 模式结构解析
标准的迭代器模式包含四个关键角色:
- Iterator(迭代器接口):定义访问和遍历元素的接口
- ConcreteIterator(具体迭代器):实现迭代器接口,跟踪遍历进度
- Aggregate(聚合接口):定义创建相应迭代器对象的接口
- ConcreteAggregate(具体聚合):实现创建迭代器的接口,返回具体迭代器实例
3. 实战示例:白名单过滤器
下面通过一个实际案例展示迭代器模式的强大威力:
// 迭代器接口
public interface Iterator<T> {
boolean hasNext();
T next();
}
// 具体迭代器实现
public class WhiteListIterator implements Iterator<String> {
private final List<String> items;
private int position;
public WhiteListIterator(List<String> items) {
this.items = items.stream()
.filter(item -> item.startsWith("VALID_"))
.collect(Collectors.toList());
this.position = 0;
}
@Override
public boolean hasNext() {
return position < items.size();
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return items.get(position++);
}
}
// 聚合接口
public interface Aggregate<T> {
Iterator<T> createIterator();
}
// 具体聚合实现
public class WhiteListCollection implements Aggregate<String> {
private final List<String> items = new ArrayList<>();
public void addItem(String item) {
items.add(item);
}
@Override
public Iterator<String> createIterator() {
return new WhiteListIterator(items);
}
}
// 客户端使用
public class Client {
public static void main(String[] args) {
WhiteListCollection collection = new WhiteListCollection();
collection.addItem("VALID_USER");
collection.addItem("INVALID_USER");
collection.addItem("VALID_ADMIN");
Iterator<String> iterator = collection.createIterator();
while (iterator.hasNext()) {
System.out.println("白名单项: " + iterator.next());
}
}
}
4. 模式优势与适用场景
优势:
- 支持以不同方式遍历同一个集合
- 简化了聚合类的接口
- 支持并行遍历,多个迭代器可同时操作同一集合
适用场景:
- 需要为复杂数据结构提供多种遍历方式时
- 需要统一遍历接口,屏蔽不同集合的内部差异时
- 当希望客户端代码与具体集合类型解耦时
5. 总结
迭代器模式通过将遍历机制抽象为独立对象,实现了算法与数据结构的分离,这是面向对象设计原则的完美体现。Java集合框架中的java.util.Iterator正是这一模式的经典实现,值得每一位开发者深入学习和掌握。
掌握迭代器模式不仅能够写出更优雅的代码,更能培养解耦思维,提升架构设计能力,为处理复杂业务场景打下坚实基础。
906

被折叠的 条评论
为什么被折叠?



