基本上來說,Iterator模式並沒有什麼可多說得,在STL中見得實在太多了,一般用於遍歷數據結構,其實現也相對簡單。
代碼如下:
////////////////////////////////////////////////////////////////////////// // author: Jeson Yang //date:2014.12.10 //file:main.cpp ////////////////////////////////////////////////////////////////////////// #includeusing namespace std; class Interator; class Aggregate { public: virtual ~Aggregate(){} virtual Interator* CreateItrator()=0{}; virtual int GetSize()=0{} virtual int GetItem(int index)=0{} protected: Aggregate(){} }; class ConcreteAggregate:public Aggregate { public: enum{size=3}; ConcreteAggregate() { for(int i=0;i < size;i++) m_obj[i]=i; } ~ConcreteAggregate(){} Interator* CreateItrator(); int GetItem(int index) { if(GetSize()) return m_obj[index]; else return -1; } int GetSize(){return size;} private: int m_obj[size]; }; class Interator { public: virtual ~Interator(){}; virtual void First()=0; virtual void Next()=0; virtual bool IsDone()=0; virtual int CurrentItem()=0; protected: Interator(){} }; class ConcreteInterator:public Interator { public: ConcreteInterator(Aggregate* ag,int index=0) {m_ag=ag;m_index=index;} ~ConcreteInterator(){} void First(){m_index=0;} void Next() { if(m_index != m_ag->GetSize()) m_index++; } bool IsDone(){return(m_index==m_ag->GetSize());} int CurrentItem(){return m_ag->GetItem(m_index);} private: Aggregate* m_ag; int m_index; }; Interator* ConcreteAggregate::CreateItrator() { return new ConcreteInterator(this); } void main() { Aggregate* ag=new ConcreteAggregate(); Interator* it=new ConcreteInterator(ag); for(;!(it->IsDone());it->Next()) { cout< CurrentItem()<