迭代器模式提供了一种方法顺序访问一个聚合对象中的各个元素, 而又不暴露其内部的表示
迭代器模式将元素之间的游走的责任交给迭代器, 而不是聚合对象, 让聚合的接口和实现更简洁
#ifndef Iterator_h
#define Iterator_h
#include <vector>
using std::vector;
template <typename T>
class Iterator
{
public:
virtual bool hasNext() = 0;
virtual T *next() = 0;
};
template <typename T>
class Aggregate
{
public:
virtual Iterator<T> *createIterator() = 0;
};
template <typename T>
class ConcreteIterator : public Iterator<T>
{
public:
ConcreteIterator(std::vector<T> all) : allItems(all), position(0) { }
virtual bool hasNext()
{
if (position < allItems.size())
{
return true;
}
return false;
}
virtual T *next()
{
return &allItems[position++];
}
private:
std::vector<T> allItems;
int position;
};
template <typename T>
class ConcreteAggregate : public Aggregate<T>
{
public:
ConcreteAggregate()
{
allItems.push_back(1);
allItems.push_back(2);
allItems.push_back(3);
}
virtual Iterator<T> *createIterator()
{
return new ConcreteIterator<T>(allItems);
}
private:
std::vector<T> allItems;
};
#endif
测试
#include <iostream>
#include "Iterator.h"
int main(int argc, char **argv)
{
ConcreteAggregate<int> aggregate;
Iterator<int> *it = aggregate.createIterator();
while (it->hasNext())
{
printf("%d.\n", *it->next());
}
return 0;
}