Iterator

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值