iterator模式:提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class Iterator;
template<typename T>
class AggregateIter;
template<typename T>
class Aggregate
{
public:
void addItem(T num)
{
vec_.push_back(num);
}
int count()
{
return vec_.size();
}
Iterator<T> *createIterator()
{
return new AggregateIter<T>(this);
}
T operator[](int i)
{
return vec_[i];
}
private:
vector<int> vec_;
};
template<typename T>
class Iterator
{
public:
virtual ~Iterator() {}
virtual bool hasNext() = 0;
virtual int next() = 0;
};
template<typename T>
class AggregateIter : public Iterator<T>
{
public:
AggregateIter(Aggregate<T> *agg)
{
agg_ = agg;
pos_ = 0;
}
bool hasNext()
{
return (pos_ < agg_->count());
}
int next()
{
return (*agg_)[pos_++];
}
private:
Aggregate<T> *agg_;
int pos_;
};
int main()
{
Aggregate<int> *agg = new Aggregate<int>();
for (int i = 0; i < 10; ++i)
agg->addItem(i*i);
Iterator<int> *it = agg->createIterator();
while (it->hasNext())
{
cout << it->next() << endl;
}
if (NULL != it)
{
delete it;
it = NULL;
}
if (NULL != agg)
{
delete agg;
agg = NULL;
}
return 0;
}