简介
迭代器模式:
提供一种方法顺序访问一个聚合对象的各个元素,而又不暴露该对象的内部表示。
构成
1.迭代器抽象类。
2.聚集抽象类。
3.具体迭代器类。
4.具体聚集类。
常用的场景
需要对聚集有多种方式的遍历时使用迭代器模式。
类图:
自行百度。。。
测试代码
#include <iostream>
#include <assert.h>
#include <vector>
using namespace std;
#include <string>
#include <list>
//迭代器抽象类
class Iterator
{
public:
Iterator(){};
~Iterator(){};
virtual bool hasNext() = 0;
virtual string next() = 0;
virtual string remove() = 0;
};
//聚集抽象类
class Aggregate
{
public:
Aggregate(){};
~Aggregate(){};
virtual Iterator* createIterator() = 0;
};
//迭代器具体类
class ConcrateIiterator : public Iterator
{
public:
ConcrateIiterator(Aggregate* pAggregate):
m_pAggregate(pAggregate)
{
}
bool hasNext()
{
return false;
};
string next()
{
return "";
};
string remove()
{
return "";
};
Aggregate* m_pAggregate;
};
//聚集具体类
class ConcrateAggregate : public Aggregate
{
public:
Iterator *createIterator()
{
ConcrateIiterator *iter= new ConcrateIiterator(this);
return iter;
};
};
void main()
{
ConcrateAggregate oAggregate;
Iterator* pIter = oAggregate.createIterator();
pIter->hasNext();
}