Iterator

来源:互联网 发布:重要的经济数据 编辑:程序博客网 时间:2024/04/28 14:37

#include <cstdlib>
#include <iostream>

using namespace std;
class Iterator;
class Agrregate
{
public:
  virtual ~Agrregate(){cout<<"Agrregate 基类析构"<<endl;}
  virtual int GetValue(int n) = 0;
  virtual int GetSize() = 0;
  virtual Iterator* GetIterator() = 0;
};
class ConcreteAgrregate:public Agrregate
{
  int m_Value[10];
  int nCount;
public:
  ConcreteAgrregate(){
    nCount = 10;
    for(int i = 0; i < 10; i++){
      m_Value[i] = i + 10;
    }
  }
  virtual ~ConcreteAgrregate(){
    cout<<"ConcreteAgrregate 子类析构"<<endl;
  }
  int GetValue(int n){
    return m_Value[n];
  }
  int GetSize(){
    return nCount;
  }
  Iterator* GetIterator();
};
class Iterator
{
protected:
  int m_Index;
  Agrregate* m_pAgrregate;
public:
  Iterator(Agrregate* p):m_Index(0),m_pAgrregate(p){}
  virtual ~Iterator(){cout<<"Iterator 基类析构"<<endl;}
  virtual void First() = 0;
  virtual void Next() = 0;
  virtual bool IsDone() = 0;
  virtual int GetValue() = 0;
};
class ConcreteIterator:public Iterator
{
public:
  ConcreteIterator(ConcreteAgrregate* p):Iterator(p){}
  virtual ~ConcreteIterator(){cout<<"ConcreteIterator 子类析构"<<endl;}
  virtual void First(){m_Index = 0;}
  virtual void Next(){m_Index++;}
  virtual bool IsDone(){
    if(m_pAgrregate->GetSize() == m_Index){
      return true;
    }else{
      return false;
    }
  }
  virtual int GetValue(){
    return m_pAgrregate->GetValue(m_Index);
  }
};
Iterator* ConcreteAgrregate::GetIterator(){
  return new ConcreteIterator(this);
}
void Do(Iterator* pIt)
{
  pIt->First();
  while(pIt->IsDone() == false){
    cout<<pIt->GetValue()<<endl;
    pIt->Next();
  }
  delete pIt;
}
int main(int argc, char *argv[])
{
    Agrregate* pAgrr = new ConcreteAgrregate();
    Do(pAgrr->GetIterator());
    delete pAgrr;
    system("PAUSE");
    return EXIT_SUCCESS;
}

原创粉丝点击