行为型 简单

迭代器模式

Iterator Pattern

提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

概述

迭代器模式是一种行为设计模式,让你能在不暴露集合底层表现形式(列表、栈和树等)的情况下遍历集合中所有的元素。

适用场景

  • 当集合背后有复杂的数据结构,希望对客户端隐藏时
  • 当需要减少程序中重复的遍历代码时
  • 当希望代码能够遍历不同的甚至是无法预知的数据结构时

优点

  • +单一职责原则:将遍历算法从集合类中分离出来
  • +开闭原则:可以实现新类型的集合和迭代器而不影响现有代码
  • +可以并行遍历同一集合,因为每个迭代器对象都包含其自身的遍历状态

缺点

  • 对于某些特殊集合,使用迭代器可能比直接遍历效率低

结构

classDiagram class Iterator { <<interface>> +hasNext() boolean +next() T } class Aggregate { <<interface>> +createIterator() Iterator } class ConcreteIterator { -collection: T[] -position: int +ConcreteIterator(collection) +hasNext() boolean +next() T } class ConcreteAggregate { -items: T[] +createIterator() Iterator +addItem(item: T) +getCount() int +getItem(index: int) T } class Client { +main() } Iterator <|.. ConcreteIterator Aggregate <|.. ConcreteAggregate ConcreteIterator --> ConcreteAggregate : traverses ConcreteAggregate ..> ConcreteIterator : creates Client ..> Iterator : uses Client ..> Aggregate : uses style Iterator fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style Aggregate fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style ConcreteIterator fill:#fff3e0,stroke:#f57c00,stroke-width:2px style ConcreteAggregate fill:#fff3e0,stroke:#f57c00,stroke-width:2px style Client fill:#f5f5f5,stroke:#616161,stroke-width:1px

交互演示

顺序访问聚合对象元素
Collection
🍎
🍌
🍇
🍊
Iteratorindex: 0hasNext: true
当前元素:

生活类比

迭代器就像是导游

博物馆导游

导游(迭代器)带领游客(客户端)参观博物馆(集合),游客不需要知道博物馆的内部布局。

代码实现

Example.java

实际应用

Java Iterator

Java 集合框架中的 Iterator 是迭代器模式的典型应用,所有集合类都实现了 Iterable 接口。

Example.java

C++ STL 迭代器

C++ 标准模板库提供了丰富的迭代器类型,包括输入、输出、前向、双向和随机访问迭代器。

Example.java

Python 迭代器协议

Python 的 for 循环和生成器都基于迭代器协议,任何实现了 __iter__ 和 __next__ 的对象都可以被迭代。

Example.java

练习

1

迭代器模式的主要目的是什么?

2

迭代器模式可以让客户端同时遍历同一个集合的多个副本

3

以下哪个不是迭代器模式的优点?