标签:设计模式 iterator designpattern
STL中的集合都有Iterator,Iterator模式的作用是遍历集合中的元素。它的实现原理为把遍历封装到一个类中进行(Iterator类),这样避免了暴露这个聚合对象内部。
Iterator模式如下图:
实现:
Aggregate.h
#ifndef AGGREGATE_H_
#define AGGREGATE_H_
typedef int Object;
class Iterator;
class Aggregate
{
public:
Aggregate(){}
virtual ~Aggregate(){}
virtual Iterator* CreateIterator()=0;
virtual Object GetItem(int idx)=0;
virtual int GetSize()=0;
protected:
};
class ConcreteAggregate:public Aggregate
{
public:
//enum{SIZE=3};
static const int SIZE=3;
ConcreteAggregate();
~ConcreteAggregate();
Iterator* CreateIterator();
Object GetItem(int idx);
int GetSize();
private:
Object objs_[SIZE];
};
#endif //AGGREGATE_H_
Aggregate.cpp
#include"Aggregate.h"
#include "Iterator.h"
#include <iostream>
ConcreteAggregate::ConcreteAggregate()
{
for (int i = 0; i < SIZE; ++i)
objs_[i] = i;
}
ConcreteAggregate::~ConcreteAggregate()
{}
Iterator* ConcreteAggregate::CreateIterator()
{
return new ConcreteIterator(this, 0);
}
Object ConcreteAggregate::GetItem(int idx)
{
if (idx < GetSize())
return objs_[idx];
else
return -1;
}
int ConcreteAggregate::GetSize()
{
return SIZE;
}
Iterator.h
#ifndef ITERATOR_H_
#define ITERATOR_H_
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();
};
class ConcreteIterator :public Iterator
{
public:
ConcreteIterator(Aggregate* ag, int idx = 0);
~ConcreteIterator();
void First();
void Next();
bool IsDone();
Object CurrentItem();
private:
Aggregate* ag_;
int idx_;
};
#endif
Iterator.cpp
#include"Aggregate.h"
#include "Iterator.h"
#include <iostream>
Iterator::Iterator()
{}
Iterator::~Iterator()
{}
ConcreteIterator::ConcreteIterator(Aggregate* ag, int idx)
{
ag_ = ag;
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();
}
main.cpp
#include "Aggregate.h"
#include "Iterator.h"
#include <iostream>
int main()
{
Aggregate* ag = new ConcreteAggregate();
for (Iterator* it = new ConcreteIterator(ag); !it->IsDone(); it->Next())
{
std::cout << it->CurrentItem() << std::endl;
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:设计模式 iterator designpattern
原文地址:http://blog.csdn.net/kangroger/article/details/48034811