标签:c++ 设计模式
#include "stdafx.h" #include <iostream> #include <vector> using namespace std; template<typename T > class Iterator { public: virtual ~Iterator(){}; virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() const = 0; virtual T* CurrentItem() = 0; }; template<typename T > class ConcreteAggregate ; template<typename T > class Aggregate { public: virtual ~Aggregate() {}; virtual Iterator< T>* CreateIterator() = 0; }; template<typename T > class ConcreteIterator :public Iterator <T > { private: ConcreteAggregate<T >* m_pAggre; int current = 0; public: virtual ~ConcreteIterator() { delete m_pAggre; } ConcreteIterator( ConcreteAggregate<T >* pAggre ) :m_pAggre(pAggre), current(0) {} virtual void First() { current = 0; } virtual void Next() { if (current < m_pAggre->GetLen()) ++current; } virtual bool IsDone() const { return (current >= m_pAggre->GetLen()); } virtual T* CurrentItem() { if (current <= m_pAggre->GetLen()) return &(*m_pAggre)[current]; else return NULL; } }; template<typename T > class ConcreteAggregate :public Aggregate <T > { private: vector< T> m_Data; public: ConcreteAggregate() { m_Data.push_back(1); m_Data.push_back(2); m_Data.push_back(3); } virtual Iterator< T>* CreateIterator() { return new ConcreteIterator<T >(this ); } T& operator[]( int index) { return m_Data[ index]; } int GetLen() { return m_Data.size(); } };
// IteratorPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Iterator.h" #include <iostream> int _tmain (int argc , _TCHAR * argv []) { Aggregate< int>* pAgg = new ConcreteAggregate<int >(); Iterator< int>* it = pAgg->CreateIterator(); for (it->First(); !it->IsDone(); it->Next()) { std::cout <<*( it->CurrentItem() )<< std::endl; } getchar(); return 0; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/27190095