迭代器模式

提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Iterator {
public:
virtual string first() = 0;
virtual string next() = 0;
virtual bool isDone() const = 0;
virtual string current() = 0;

virtual ~Iterator() {}
};
class Aggregate {//聚合类
public:
virtual void push(const string& s) = 0;
virtual string pop(int index) = 0;
virtual int Count() const = 0;
virtual Iterator* createIterator() = 0;

virtual ~Aggregate() {}
};

class ConcreteIterator :public Iterator {
private:
Aggregate* aggregate;
int index;
public:
ConcreteIterator(Aggregate* aggregate) :aggregate(aggregate),index(0) {}

string first() override {
if (aggregate->Count() == 0)
return string();
return aggregate->pop(0);
}
string next() override {
if (++index >= aggregate->Count())
return string();
return aggregate->pop(index);
}
string current() override {
if (index >= aggregate->Count()) {
return string();
}
return aggregate->pop(index);
}
bool isDone() const override {
return index < 0 || index >= aggregate->Count();
}
};

class ConcreteAggregate :public Aggregate {
private:
vector<string> strs;
public:
void push(const string& s) override {
return strs.emplace_back(s);
}
string pop(int index) override {
if (index >= strs.size())
return string();
return strs.at(index);
}
int Count() const override {
return strs.size();
}
Iterator* createIterator() {//创建相应迭代器
//多态迭代器(此处依赖于具体类的实现,为了代码的稳定性,可以结合工厂模式)
return new ConcreteIterator(this);
}
};


int main()
{
Aggregate* aggregate = new ConcreteAggregate();
aggregate->push("hello");
aggregate->push("world");

Iterator* iter = aggregate->createIterator();
cout << iter->first() << endl;
while (!iter->isDone())
{
cout << iter->next();
}
delete aggregate, iter;
return 0;
}

结果如下:
C++设计模式——迭代器模式(Iterator)_ide
迭代器中,主要涉及迭代器抽象类和聚合抽象类(定义创建相应迭代器对象的接口)。具体聚合类中实现创建相应迭代器的接口。在C++标准库中,已经实现了迭代器,可直接使用。