template <class ElemType> class Iterator; template<class ElemType> class Aggregrate //抽象的容器类,定义了产生迭代器类的接口 { public: virtual ~Aggregrate(){} virtual Iterator<ElemType>* createIterator() = 0; virtual ElemType* operator[](int) = 0; virtual int size() = 0; virtual void add(ElemType) = 0; }; template<class ElemType> class ConcreteAggregrate : public Aggregrate<ElemType> { public: ~ConcreteAggregrate(){} Iterator<ElemType>* createIterator() { return new ConcreteIterator<ElemType>(this); } ElemType* operator[](int i) { return &mData[i]; } int size() { return mData.size(); } void add(ElemType data) { mData.push_back(data); } private: vector<ElemType> mData; }; template<class ElemType> class Iterator //抽象迭代器类,定义了遍历和访问元素的接口 { public: virtual ~Iterator(){} virtual void begin() = 0; virtual bool isEnd() = 0; virtual void previous() = 0; virtual void next() = 0; virtual ElemType* get() = 0; }; template<class ElemType> class ConcreteIterator :public Iterator<ElemType> //具体迭代器类,实现了遍历和访问元素的接口 { public: ConcreteIterator(Aggregrate<ElemType> *agg) :magg(agg), current(0){} ~ConcreteIterator(){} void next() { current++; } void previous() { current--; } void begin() { current = 0; } bool isEnd() { return current == magg->size(); } ElemType* get() { return (*magg)[current]; } private: Aggregrate<ElemType> *magg; int current; }; int main() { Aggregrate<int> *agg = new ConcreteAggregrate<int>(); Iterator<int> *iter = new ConcreteIterator<int>(agg); agg->add(1); agg->add(2); agg->add(3); for (iter->begin(); !iter->isEnd(); iter->next()) cout << *iter->get() << endl; delete agg; delete iter; return 0; }