设计模式--迭代器模式C++实现
迭代器模式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());
}