1. 定义
提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露(稳定)该对象的内部表示。
2. 适用场景
- 在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们希望在不暴露真内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为“同一种算法在多种集合对象上进行操作”提供了可能。
- 使用面向对象技术将这种遍历机制抽象为“迭代器对象”为”应对变化中的集合对象” 提供了一种优雅的方式。
3. 要点总结
- 迭代抽象: 访问一个聚合对象的内容而无需暴露它的内部表示。
- 迭代多态:为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作。
- 迭代器的健壮性考虑: 遍历的同时更改迭代器所在的集合结构,会导致问题。
4. Demo
template<typename T>
class Iterator
{
public:
virtual void first() = 0;
virtual void next() = 0;
virtual bool isDone() const = 0;
virtual T& current() = 0;
};
template<typename T>
class MyCollection{
public:
Iterator<T> GetIterator(){
//...
}
};
template<typename T>
class CollectionIterator : public Iterator<T>{
MyCollection<T> mc;
public:
CollectionIterator(const MyCollection<T> & c): mc(c){ }
void first() override {
}
void next() override {
}
bool isDone() const override{
}
T& current() override{
}
};
void MyAlgorithm()
{
MyCollection<int> mc;
Iterator<int> iter= mc.GetIterator();
for (iter.first(); !iter.isDone(); iter.next()){
cout << iter.current() << endl;
}
}
本专栏文章:
- 01-C++面向对象设计原则
- 02-C++模式概述
- 03-模板方法(Template Method)
- 04-策略模式(Strategy)
- 05-观察者模式(Observer)
- 06-装饰模式(Decorator)
- 07-桥模式(Bridge)
- 08-工厂方法(Factory Method)
- 09-抽象工厂(Abstract Factory)
- 10-原型模式(Prototype)
- 11-构建器(Builder)
- 12-单件模式(Singleton)
- 13-享元模式(Flyweight)
- 14-门面模式(Façade)
- 15-代理模式(Proxy)
- 16-适配器(Adapter)
- 17-中介者(Mediator)
- 18-状态模式(State)
- 19-备忘录(Memento)
- 20-组合模式(Composite)
- 21-迭代器(Iterator)
- 22-职责链(Chain of Resposibility)
- 23-命令模式(Command)
- 24-访问器(Visitor)
- 25-解析器(Interpreter)
- 26-C++设计模式总结