迭代器模式C++
2018-05-16 本文已影响0人
涵仔睡觉
迭代器模式,提供了一种方法顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表示。
迭代器模式结构图
迭代器基本代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Iterator { // 迭代器抽象类
public:
virtual string First() = 0;
virtual string Next() = 0;
virtual bool IsDone() = 0;
virtual string CurrentItem() = 0;
virtual ~Iterator(){}
};
class Aggregate { // 聚集抽象类
public:
virtual Iterator* CreateIterator() = 0;
virtual void Push(string s) = 0;
virtual string Pop(int index) = 0;
virtual int Count() = 0;
};
class ConcreteIterator : public Iterator { // 具体迭代器类
private:
Aggregate* aggregate;
int index;
public:
ConcreteIterator(Aggregate* a) {
index = 0;
aggregate = a;
}
string First() { return aggregate->Pop(0); }
string Next() {
string str;
index++;
if (index < aggregate->Count()) str = aggregate->Pop(index);
return str;
}
bool IsDone() { return (index >= aggregate->Count()); }
string CurrentItem() { return aggregate->Pop(index); }
};
class ConcreteAggregate : public Aggregate {
private:
vector<string> items;
Iterator* iterator;
public:
ConcreteAggregate() {
iterator = NULL;
items.clear();
}
~ConcreteAggregate() {
if (iterator){
delete iterator;
iterator = NULL;
}
}
Iterator* CreateIterator() {
if (iterator == NULL) iterator = new ConcreteIterator(this);
return iterator;
}
int Count() { return items.size(); }
void Push(string s) { items.push_back(s); }
string Pop(int index) {
string str;
if (index < Count()) str = items[index];
return str;
}
};
int main() {
ConcreteAggregate* ca = new ConcreteAggregate();
ca->Push("Hello");
ca->Push("World");
Iterator* it = new ConcreteIterator(ca);
while(!it->IsDone()) {
cout << it->CurrentItem() << endl;
it->Next();
}
delete it;
delete ca;
return 0;
}
应用场景
- 当需要访问一个聚合对象,而且不管这些对象时什么都需要遍历的时候,就该考虑迭代器模式;
- 需要对聚集有多种方式遍历时,可以考虑用迭代器模式。
迭代器模式就说分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可以让外部代码透明地访问集合内部的数据。