目的:将数据的存储和数据的查询分开,降低数据的耦合性
继承关系图:
例子:
//定义迭代器接口 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; virtual T getItem(int index) = 0; virtual int getSize() = 0; virtual void setItem(T t) = 0; };
//迭代器的具体实现类 template<typename T> class IteratorImp: public Iterator<T> { Aggregate<T>* p; int index; public: IteratorImp(Aggregate<T>* aggregate) { p = aggregate; index = 0; } bool hasNext() { if(index < p->getSize()) { return true; } else { return false; } } T next() { return p->getItem(index++); } };
//集合的具体实现类 template<typename T> class AggregateImp: public Aggregate<T> { vector<T> data; public: Iterator<T>* createIterator() //这一步是关键,将迭代器和集合挂钩 { //根据集合初始化迭代器并返回迭代器 return new IteratorImp<T>(this); } T getItem(int index) { return data[index]; } int getSize() { return data.size(); } void setItem(T t) { data.push_back(t); } };
int main() { Aggregate<int>* d = new AggregateImp<int>(); Iterator<int>* iterator = d->createIterator(); d->setItem(1); d->setItem(3); d->setItem(4); d->setItem(2); while(iterator->hasNext()) { cout << iterator->next() <<endl; } return 0; }