1.目的
当需要遍历(单种方式或多种方式)遍历一个组合对象时,使用遍历模式。该模式类似与将容器的接口进行封装,不对外直接暴露容器的接口的做法类似。
2.代码
#ifndef ITERATOR_H_
#define ITERATOR_H_
#include <list>
#include <string>
using namespace std;
class PersonForIterator
{
public:
PersonForIterator()
{}
string getName()
{
return name;
}
PersonForIterator(string arg)
{
name = arg;
}
private:
string name;
};
class Aggregate
{
public:
virtual ~Aggregate()
{}
void insert(PersonForIterator& arg)
{
lists.push_back(arg);
}
public:
list<PersonForIterator> lists;
};
class Iterator
{
public:
Iterator(Aggregate& agg):agg(agg)
{
iter = agg.lists.begin();
}
PersonForIterator& first()
{
return *(agg.lists.begin());
}
PersonForIterator& next()
{
iter++;
return *iter;
}
bool isDone()
{
return (iter == agg.lists.end());
}
private:
Aggregate& agg;
list<PersonForIterator>::iterator iter;
};
#endif /* ITERATOR_H_ */
#include "Iterator.h"
#include <iostream>
void iterator()
{
PersonForIterator p1("Tom");
PersonForIterator p2("Allen");
PersonForIterator p3("John");
PersonForIterator p4("Jim");
Aggregate agg;
agg.insert(p1);
agg.insert(p2);
agg.insert(p3);
agg.insert(p4);
Iterator it(agg);
PersonForIterator p = it.first();
while(!it.isDone())
{
cout<<p.getName()<<endl;
p = it.next();
}
}
输出:
Tom
Allen
John
Jim