Iterator
迭代器模式是在不暴露集合底层数据格式的情况下对集合进行遍历
- 当集合/对象内部存在复杂的数据结构时,出于安全性或便利性考虑采用该模式
- 简单集合会增加代码复杂性,特殊集合可能效率不如直接遍历
例如复制容器
1 | // direct |
使用迭代器模式时,格式更加简洁,且无需关注容器内部数据结构,更具灵活性和通用性
CPP
基本结构
Member | FullName | Description |
---|---|---|
聚合接口 | Aggregate | 定义遍历的集合 |
具体聚合类 | ConcreteAggregate | 维护集合类 |
迭代器接口 | Iterator | 定义遍历接口 |
具体迭代器类 | ConcreteIterator | 实现迭代器对集合进行遍历 |
UML结构图
实现步骤
- 定义迭代器接口
1 | class Iterator { |
- 定义聚合接口 (包含迭代器)
1 | class Aggregate { |
- 定义具体聚合类
1 | class IntCollection : public Aggregate { |
- 定义具体迭代器类
1 | class IntIterator : public Iterator { |
- 使用迭代器
1 | IntCollection collection; |
Fortran
fortran 实现迭代器模式主要问题在于迭代器和容器包含相互的指针,该过程难以实现,虽然通过 复制 能够完成数据传递,但会占用额外空间
一种可能的方案是将 create_iterator
放在迭代器类下,将 Aggregate
实例对象指针作为输入参数
代码存在段错误,需要进一步调试
1 | module iterator_module |
Reference
refactoringguru | 迭代器模式
扣丁梦想家 | 设计模式教程:迭代器模式(Iterator Pattern)
supdriver | 设计模式的C++实现(4)——迭代器Iterator