1.Iterator模式用來解決對一個聚合對象的遍歷問題,將對聚合的遍歷封裝到一個類中進行,這樣就避免了暴露這個聚合對象的內部表示的可能.ios
2.Iterator 模式結構圖ide
3.實現this
1 #ifndef _AGGREGATE_H_ 2 #define _AGGREGATE_H_ 3 4 class Iterator; 5 typedef int Object; 6 class Interator; 7 8 class Aggregate 9 { 10 public: 11 virtual ~Aggregate(); 12 virtual Iterator* CreateIterator() = 0; 13 virtual Object GetItem(int idx) = 0; 14 virtual int GetSize() = 0; 15 16 protected: 17 Aggregate(); 18 19 private: 20 }; 21 22 class ConcreteAggregate:public Aggregate 23 { 24 public: 25 enum 26 { 27 SIZE = 3 28 }; 29 ConcreteAggregate(); 30 ~ConcreteAggregate(); 31 Iterator* CreateIterator(); 32 Object GetItem(int idx); 33 int GetSize(); 34 35 protected: 36 private: 37 Object _objs[SIZE]; 38 }; 39 40 #endif
1 #include "Aggregate.h" 2 #include "Iterator.h" 3 #include <iostream> 4 5 using namespace std; 6 7 Aggregate::Aggregate() 8 { 9 10 } 11 Aggregate::~Aggregate() 12 { 13 14 } 15 ConcreteAggregate::ConcreteAggregate() 16 { 17 for (int i = 0; i < SIZE; i++) 18 _objs[i] = i; 19 } 20 ConcreteAggregate::~ConcreteAggregate() 21 { 22 23 } 24 Iterator* ConcreteAggregate::CreateIterator() 25 { 26 return new ConcreteIterator(this); 27 } 28 Object ConcreteAggregate::GetItem(int idx) 29 { 30 if (idx < this->GetSize()) 31 return _objs[idx]; 32 else 33 return -1; 34 } 35 int ConcreteAggregate::GetSize() 36 { 37 return SIZE; 38 }
1 #ifndef _ITERATOR_H_ 2 #define _ITERATOR_H_ 3 4 class Aggregate; 5 typedef int Object; 6 7 class Iterator 8 { 9 public: 10 virtual ~Iterator(); 11 virtual void First() = 0; 12 virtual void Next() = 0; 13 virtual bool IsDone() = 0; 14 virtual Object CurrentItem() = 0; 15 16 protected: 17 Iterator(); 18 private: 19 }; 20 21 class ConcreteIterator:public Iterator 22 { 23 public: 24 ConcreteIterator(Aggregate* ag , int idx = 0); 25 ~ConcreteIterator(); 26 void First(); 27 void Next(); 28 bool IsDone(); 29 Object CurrentItem(); 30 31 protected: 32 private: 33 Aggregate* _ag; 34 int _idx; 35 }; 36 37 #endif
1 #include "Iterator.h" 2 #include "Aggregate.h" 3 #include <iostream> 4 using namespace std; 5 6 Iterator::Iterator() 7 { 8 9 } 10 Iterator::~Iterator() 11 { 12 13 } 14 ConcreteIterator::ConcreteIterator(Aggregate* ag , int idx) 15 { 16 this->_ag = ag; 17 this->_idx = idx; 18 } 19 ConcreteIterator::~ConcreteIterator() 20 { 21 22 } 23 Object ConcreteIterator::CurrentItem() 24 { 25 return _ag->GetItem(_idx); 26 } 27 void ConcreteIterator::First() 28 { 29 _idx = 0; 30 } 31 void ConcreteIterator::Next() 32 { 33 if (_idx < _ag->GetSize()) 34 _idx++; 35 } 36 bool ConcreteIterator::IsDone() 37 { 38 return (_idx == _ag->GetSize()); 39 }
1 #include "Iterator.h" 2 #include "Aggregate.h" 3 #include <iostream> 4 using namespace std; 5 6 int main(int argc,char* argv[]) 7 { 8 Aggregate* ag = new ConcreteAggregate(); 9 Iterator* it = new ConcreteIterator(ag); 10 for (; !(it->IsDone()) ; it->Next()) 11 { 12 cout<<it->CurrentItem()<<endl; 13 } 14 15 return 0; 16 }