提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。当你需要访问一个聚集对象,而且不管这些对象是什么都需要遍 历的时候,就应该考虑用迭代器模式。同时需要对聚集有多种方式遍历时,可以考虑用迭代器模式。为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪 一项等统一接口。迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集 合内部的数据。
代码如下:
#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 函数
#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; }