迭代器模式(c++实现)
迭代器模式
模式定义
迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
模式动机
- 一个聚集对象,而且不管这些对象是什么都需要遍历的时候,你就应该考虑迭代器模式。
- 你需要对聚集有多种方式遍历时,可以考虑用迭代器模式。
- 为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪一项等统一的接口。
UML类图
源码实现
- aggregate.h
#include <string>
#include <vector>
class Aggregate
{
public:
Aggregate();
void insert(std::string obj);
virtual ~Aggregate();
virtual int Count() = 0;
virtual std::string& operator[](int i) = 0;
protected:
std::vector<std::string> m_Vec;
};
- aggregate.cpp
#include "aggregate.h"
Aggregate::Aggregate()
{
}
Aggregate::~Aggregate()
{
}
void Aggregate::insert(std::string obj)
{
m_Vec.push_back(obj);
}
- iterator.h
#include "aggregate.h"
class Iterator
{
public:
Iterator(Aggregate* aggregate);
virtual ~Iterator();
virtual std::string First() = 0;
virtual std::string Next() = 0;
virtual bool IsDone() = 0;
virtual std::string CurrentItem() = 0;
protected:
Aggregate* m_Aggregate;
};
- concreteIterator.h
#include "iterator.h"
#include "aggregate.h"
class ConcreteIterator : public Iterator
{
public:
ConcreteIterator(Aggregate* aggredate);
std::string First() override;
std::string Next() override;
bool IsDone() override;
std::string CurrentItem() override;
private:
int m_CurrentIndex;
};
- concreteIterator.cpp
#include <iostream>
#include "concreteiterator.h"
ConcreteIterator::ConcreteIterator(Aggregate* aggredate)
:Iterator(aggredate)
{
m_CurrentIndex = 0;
}
std::string ConcreteIterator::First()
{
return (*m_Aggregate)[0];
}
std::string ConcreteIterator::Next()
{
m_CurrentIndex++;
if(m_CurrentIndex < m_Aggregate->Count())
return (*m_Aggregate)[m_CurrentIndex];
else
return "";
}
bool ConcreteIterator::IsDone()
{
return m_CurrentIndex >= m_Aggregate->Count() ? true : false;
}
std::string ConcreteIterator::CurrentItem()
{
return (*m_Aggregate)[m_CurrentIndex];
}
- concreteAggregate.h
#include <aggregate.h>
#include <string>
#include "iterator.h"
class ConcreteAggregate : public Aggregate
{
public:
ConcreteAggregate();
int Count() override;
std::string &operator[](int i) override;
private:
Iterator* m_Iterator;
};
- concreteAggregate.cpp
#include "concreteaggregate.h"
ConcreteAggregate::ConcreteAggregate()
{
}
int ConcreteAggregate::Count()
{
return static_cast<int>(m_Vec.size());
}
std::string& ConcreteAggregate::operator[](int i)
{
return m_Vec[size_t(i)];
}
- main.cpp
#include <iostream>
#include "concreteaggregate.h"
#include "concreteiterator.h"
using namespace std;
int main()
{
Aggregate* agt = new ConcreteAggregate();
agt->insert("王二麻子");
agt->insert("张二蛋子");
agt->insert("李二狗子");
agt->insert("王小花儿");
Iterator* i = new ConcreteIterator(agt);
while(!i->IsDone())
{
std::cout << i->CurrentItem() << " 请出示您的车票!" << std::endl;
i->Next();
}
return 0;
}
- 运行结果
王二麻子 请出示您的车票!
张二蛋子 请出示您的车票!
李二狗子 请出示您的车票!
王小花儿 请出示您的车票!
优点
迭代器模式的优点
- 迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可以让外部代码透明地访问集合内部的数据。
缺点
模式的缺点