標籤:
前言
在尋常生活其中,我們常常要使用到迭代器。比如在觀看一組圖片時,我們常常使用遍曆的方法觀看,我們並不須要詳細研究圖片的結構,僅僅須要遍曆,而且能夠將當前的遍曆狀態記錄下來,下次觀看時能夠從之前的遍曆終止點開始繼續。
即在物件導向的軟體設計中,我們常常會遇到一類集合對象。這類集合對象的內部結構可能有著各種各樣的實現。可是最重要的是有兩點是須要我們去關心的:一是集合內部的資料存放區結構,二是遍曆集合內部的資料。物件導向設計原則中有一條是類的單一職責原則。所以我們要儘可能的去分解這些職責,用不同的類去承擔不同的職責。Iterator模式就是分離了集合對象的遍曆行為。抽象出一個迭代器類來負責,這樣既能夠做到不暴露集合的內部結構,又可讓外部代碼透明的訪問集合內部的資料。
1.別人可能要用到我們的容器元素,使用迭代器能夠訪問各個元素而不暴露容器內部細節。
2.能夠有一種以上的方式遍曆容器元素
3.同一時候對容器元素進行多次遍曆。
由於迭代器會儲存當前的遍曆狀態,所以能夠通過迭代器模式來達到這樣的需求。
迭代器(Iterator)模式
又叫做遊標(Cursor)模式。GOF給出的定義為:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內部細節。
UML圖:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGl1Y2ltaW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" >
Iterator:定義迭代器訪問和遍曆元素的介面;
ConcreteIterator:實現詳細的迭代器。
Aggregate:定義的容器。建立對應迭代器對象的介面;
ConcreteAggregate:詳細的容器實現建立對應迭代器的介面,該操作返回ConcreteIterator的一個適當的執行個體。
代碼例如以下:
#include <iostream> #include <vector> using namespace std; template<class T> class Iterator; template<class T> class ConcreteIterator;//集合角色template<class T> class Aggregate{public: virtual ConcreteIterator<T> begin()=0; virtual ConcreteIterator<T> end()=0; virtual ~Aggregate(){} };template<class T> class ConcreteAggregate:public Aggregate<T> {vector<T >data; public: ConcreteAggregate() { data.push_back(1); data.push_back(2); data.push_back(3); } virtual ConcreteIterator<T> begin() { return ConcreteIterator<T>(this); } virtual ConcreteIterator<T> end() { return ConcreteIterator<T>(this,data.size()); } T& operator[](int index) { return data[index]; } };template<class T> class Iterator { public://virtual Iterator<T>& operator ++(int);//virtual Iterator<T>& operator ++();////virtual const T& operator*() const;virtual T& getCur()=0;}; template<class T> class ConcreteIterator:public Iterator<T>{private: ConcreteAggregate<T>* m_pAG;int cur; public:ConcreteIterator(ConcreteAggregate<T>*a):m_pAG(a),cur(0){} ConcreteIterator(ConcreteAggregate<T>*a,int len):m_pAG(a),cur(len){} ConcreteIterator<T>& operator ++(int){ConcreteIterator<T> ret(*this);++*this;return ret;}ConcreteIterator<T>& operator ++(){cur++;return *this;}ConcreteIterator<T>& operator =(ConcreteIterator<T>& rhs){this=rhs;return *this;}bool operator !=(ConcreteIterator<T>& rhs){return this->cur!=rhs.cur;} T& getCur() {T temp=(*m_pAG)[cur];return temp;}};int main() { Aggregate<int> * aggr =new ConcreteAggregate<int>(); ConcreteIterator<int> it=aggr->begin(); //it++;for(;it!=aggr->end();it++) { cout<<it.getCur();} //delete it; delete aggr; return 0; }
感覺自己寫的有點問題。主要想重載操作符++跟*之類的。老是不成功,想做成跟c++裡面的迭代器一樣,可是詳細裡面裡面怎麼實現還不清楚。要是誰有資料能把連結發給我看看就謝謝啦~
著作權聲明:本文博主原創文章。部落格,未經同意不得轉載。
設計模式: 迭代模式