1.迭代器模式简介
迭代器模式提供了一种方法顺序访问一个聚合对象中的各个元素,而又无需暴露该对象的内部实现,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。
2.源码实现
#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:
Aggregate(){};
virtual ~Aggregate(){};
virtual int Count() = 0;
virtual void Push(const string &strValue) = 0;
virtual string Pop(const int index) = 0;
virtual Iterator *CreateIterator() = 0;
};
class ConcreteIterator : public Iterator
{
public:
ConcreteIterator(Aggregate *pAggregate) : Iterator()
{
m_nCurrent = 0;
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:
int m_nCurrent;
Aggregate *m_Aggregate;
};
class ConcreteAggregate : public Aggregate
{
public:
ConcreteAggregate() : m_pIterator(NULL)
{
m_vecItems.clear();
}
~ConcreteAggregate()
{
if(m_pIterator != NULL)
{
delete m_pIterator;
m_pIterator = NULL;
}
}
Iterator *CreateIterator()
{
if(m_pIterator == NULL)
{
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 index)
{
string strRet;
if(index < Count())
{
strRet = m_vecItems[index];
}
return strRet;
}
private:
Iterator *m_pIterator;
vector<string> m_vecItems;
};
int main(int argc, char **argv)
{
ConcreteAggregate *pName = new ConcreteAggregate();
if(pName == NULL)
return -1;
pName->Push("hello");
pName->Push("world");
pName->Push("cxue");
Iterator *iter = NULL;
iter = pName->CreateIterator();
if(iter != NULL)
{
string strItem = iter->First();
while(!iter->IsEnd())
{
cout << iter->GetCur() << " is ok" << endl;
iter->Next();
}
}
delete pName;
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
hello is ok
world is ok
cxue is ok
网友评论