提供一種方法順序訪問一個聚合對象中各個元素,而又不暴露該對象的內部表示。當你須要訪問一個彙集對象,並且無論這些對象是什麼都須要遍 歷的時候,就應該考慮用迭代器模式。同時須要對彙集有多種方式遍歷時,能夠考慮用迭代器模式。爲遍歷不一樣的彙集結構提供如開始、下一個、是否結束、當前哪 一項等統一接口。迭代器模式就是分離了集合對象的遍歷行爲,抽象出一個迭代器類來負責,這樣既能夠作到不暴露集合的內部結構,又可以讓外部代碼透明地訪問集 合內部的數據。ios
代碼以下:函數
#include <iostream> #include <string> #include <vector> using namespace std; class Iterator { public: Iterator(){}; virtual ~Iterator(){}; virtual string First() = 0; virtual string Next() = 0; virtual string GetCur() = 0; virtual bool IsEnd() = 0; }; class Aggregate { public: virtual int Count() = 0; virtual void Push(const string& strValue)=0; virtual string Pop(const int nIndex)=0; virtual Iterator* CreateIterator() = 0; }; class ConcreteIterator : public Iterator { public: ConcreteIterator(Aggregate* pAggregate):m_nCurrent(0),Iterator() { m_Aggregate = pAggregate; } string First() { return m_Aggregate->Pop(0); } string Next() { string strRet; m_nCurrent++; if(m_nCurrent < m_Aggregate->Count()) { strRet = m_Aggregate->Pop(m_nCurrent); } return strRet; } string GetCur() { return m_Aggregate->Pop(m_nCurrent); } bool IsEnd() { return ((m_nCurrent >= m_Aggregate->Count()) ? true: false); } private: Aggregate* m_Aggregate; int m_nCurrent; }; class ConcreteAggregate : public Aggregate { public: ConcreteAggregate():m_pIterator(NULL) { m_vecItems.clear(); } ~ConcreteAggregate() { if(NULL != m_pIterator) { delete m_pIterator; m_pIterator = NULL; } } Iterator* CreateIterator() { if(NULL == m_pIterator) { m_pIterator = new ConcreteIterator(this); } return m_pIterator; } int Count() { return m_vecItems.size(); } void Push(const string& strValue) { m_vecItems.push_back(strValue); } string Pop(const int nIndex) { string strRet; if(nIndex < Count()) { strRet = m_vecItems[nIndex]; } return strRet; } private: vector<string> m_vecItems; Iterator* m_pIterator; };
main 函數this
#include "iterator.h" int main() { ConcreteAggregate* pName = NULL; pName = new ConcreteAggregate(); if(NULL != pName) { pName->Push("hello"); pName->Push("word"); pName->Push("cxue"); } Iterator* iter = NULL; iter = pName->CreateIterator(); if(NULL != iter) { string strItem = iter->First(); while(!iter->IsEnd()) { cout << iter->GetCur() << " is ok" << endl; iter->Next(); } } system("pause"); return 0; }