Iterator迭代器模式是一種“數據結構”模式
- 常常有一些組件在內部具有特定的數據結構。如果讓客戶程序依賴這些特定的數據結構,將極大地破壞組件的複用。這時候,將這些特定數據結構封裝在內部,在外部提供統一的接口,來實現與特定數據結構無關的訪問,是一種行之有效的解決方案
動機
- 在軟件構建過程中,集合對象內部結構常常變化各異。但對於這些集合對象,我們希望在不暴露其內部結構的同時,可以讓外部客戶代碼透明地訪問其中包含的元素;同時這種“透明遍歷”也爲“同一種算法在多種集合對象上進行操作”提供了可能
- 使用面向對象技術將這種遍歷機制抽象爲“迭代器對象”爲“應對變化中的集合對象”提供了一種優雅的方式
定義
- 提供一種方法順序訪問一個聚合對象的各個元素,而又不暴露(穩定)該對象的內部表示
結構
代碼對比
iterator.cpp
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;
}
}
要點總結
- 基於模板的迭代器(STL與泛型編程)要優於基於虛函數的迭代器,其成本更低
- 迭代抽象:訪問一個聚合對象的內容而無需暴露它的內部表示
- 迭代多態:爲遍歷不同的集合結構提供一個統一的接口,從而支持同樣的算法在不同的集合結構上進行操作
- 迭代器的健壯性考慮:遍歷的同時更改迭代器所在的集合結構,會導致問題