码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式--迭代器模式C++实现

时间:2016-03-28 15:12:57      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

迭代器模式C++实现

1定义 

他提供一种方法访问一个容器对象中的各个元素,而不暴漏该对象内部细节

注:迭代器是为容器服务的。迭代器模式提供了遍历容器的方便性,容器只管理增减元素就好,需要遍历时交给迭代器就好。

2类图

技术分享

角色分析

Iterator抽象迭代,定义访问和遍历元素的接口,一般都是固定接口:first,next,IsDone/last

ConcreteIterator具体迭代器,实现迭代器接口,完成容器元素的遍历

Aggregate抽象容器,负责提供具体迭代器角色的接口,必然提供一个CreateIterator的方法。

ConcreteAggregate具体容器,实现接口定义的方法,创建出容纳迭代器的对象

3实现

class Iterator;
typedef int Object;
class Interator;
class Aggregate
{
public:
  virtual ~Aggregate();
  virtual Iterator* CreateIterator() = 0;
  virtual Object GetItem(int idx) = 0;
  virtual int GetSize() = 0;
protected:
  Aggregate();
private:
};

class ConcreteAggregate:public Aggregate
{
public:
  enum {SIZE = 3};
  ConcreteAggregate();
  ~ConcreteAggregate();
  Iterator* CreateIterator();
  Object GetItem(int idx);
  int GetSize();
protected:

private:
  Object _objs[SIZE];
};

#include <iostream>
using namespace std;
Aggregate::Aggregate()
{
}
Aggregate::~Aggregate()
{
}
ConcreteAggregate::ConcreteAggregate()
{
  for (int i = 0; i < SIZE; i++)
  _objs[i] = i;
}
ConcreteAggregate::~ConcreteAggregate()
{
}
Iterator* ConcreteAggregate::CreateIterator()
{
  return new ConcreteIterator(this);
}
Object ConcreteAggregate::GetItem(int idx)
{
  if (idx < this->GetSize())
  return _objs[idx];
else

  return -1;

}
int ConcreteAggregate::GetSize()
{
  return SIZE;
}

class Aggregate;
typedef int Object;
class Iterator
{
public:
  virtual ~Iterator();
  virtual void First() = 0;
  virtual void Next() = 0;
  virtual bool IsDone() = 0;
  virtual Object CurrentItem() = 0;
protected:
  Iterator();
private:
};
class ConcreteIterator:public Iterator
{
public:
  ConcreteIterator(Aggregate* ag , int idx = 0);
  ~ConcreteIterator();
  void First();

  void Next();
  bool IsDone();
  Object CurrentItem();
protected:
private:
  Aggregate* _ag;
  int _idx;
};

Iterator::Iterator()
{
}
Iterator::~Iterator()
{
}
ConcreteIterator::ConcreteIterator(Aggregate* ag , int idx)
{
  this->_ag = ag;
  this->_idx = idx;
}
ConcreteIterator::~ConcreteIterator()
{
}

Object ConcreteIterator::CurrentItem()
{
  return _ag->GetItem(_idx);
}
void ConcreteIterator::First()
{
  _idx = 0;
}
void ConcreteIterator::Next()
{
  if (_idx < _ag->GetSize())
  _idx++;
}
bool ConcreteIterator::IsDone()
{
  return (_idx == _ag->GetSize());
}

设计模式--迭代器模式C++实现

标签:

原文地址:http://www.cnblogs.com/lang5230/p/5328568.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!