迭代器模式
定义:提供一种方法顺序访问一个集合对象中的元素,但是又不暴露该对象的内部显示
这里采用了类模板来定义类,强化对模板的运用。
代码:
#include <iostream>
#include <list>
#include <vector>
using namespace std;
//抽象迭代器类
template<typename T>
class Iterator
{
public:
virtual T firstItem() = 0;
virtual T nextItem() = 0;
virtual T currentItem() = 0;
virtual bool isEnd() = 0;
};
//抽象聚合类
template<typename T>
class Aggregate
{
public:
virtual int count() = 0;
virtual void pushItem(const T& str) = 0;
virtual T removeItem(const int index) = 0;
virtual Iterator<T>* createIterator() = 0;
};
//具体聚合类
template<typename T>
class ConcreteAggregate :Aggregate<T>
{
public:
ConcreteAggregate() :m_pIter(nullptr){}
~ConcreteAggregate()
{
if (m_pIter)
{
delete m_pIter;
m_pIter = nullptr;
}
}
int count()
{
return m_listItem.size();
}
void pushItem(const T& str)
{
m_listItem.push_back(str);
}
T removeItem(const int index)
{
T res;
if (index < count())
{
res = m_listItem[index];
}
return res;
}
Iterator<T>* createIterator()
{
m_pIter = new ConcreteIterator<T>(this);
return m_pIter;
}
private:
vector<T> m_listItem;
Iterator<T> *m_pIter;
};
//具体迭代器类
template<typename T>
class ConcreteIterator :public Iterator<T>
{
public:
ConcreteIterator(Aggregate<T>* pA) :m_cnt(0), m_pConcreteA(nullptr)
{
m_pConcreteA = pA;
}
T firstItem()
{
return m_pConcreteA->removeItem(0);
}
T nextItem()
{
m_cnt++;
if (m_cnt < m_pConcreteA->count())
{
return m_pConcreteA->removeItem(m_cnt);
}
return T();
}
T currentItem()
{
return m_pConcreteA->removeItem(m_cnt);
}
bool isEnd()
{
return ((m_cnt >= m_pConcreteA->count()) ? true : false);
}
private:
Aggregate<T> *m_pConcreteA;
int m_cnt;
};
//客户端
int main()
{
ConcreteAggregate<string> *p = new ConcreteAggregate < string > ;
p->pushItem("宫保鸡丁");
p->pushItem("鱼香肉丝");
p->pushItem("翡翠白菜");
p->pushItem("青椒牛肉");
Iterator<string> *it = p->createIterator();
if (it)
{
string item = it->firstItem();
cout << "胖虎今天要吃的是菜是" << endl;
while (!it->isEnd())
{
cout << it->currentItem().c_str() << endl;
it->nextItem();
}
}
cout << "====================" << endl;
ConcreteAggregate<int> *p1 = new ConcreteAggregate<int>;
p1->pushItem(999);
p1->pushItem(888);
p1->pushItem(666);
p1->pushItem(555);
Iterator<int> *pIter = p1->createIterator();
if (pIter)
{
int item = pIter->firstItem();
cout << "小明今天要学习的数字是" << endl;
while (!pIter->isEnd())
{
cout << pIter->currentItem() << endl;
pIter->nextItem();
}
}
if (p)
{
delete p;
p = nullptr;
}
if (p1)
{
delete p1;
p1 = nullptr;
}
return 0;
}
效果: