迭代器模式是一种行为型设计模式,用于提供一种遍历集合对象的统一接口。在C++中,可以使用以下步骤实现迭代器模式:
#include <iostream>
#include <vector>
// 抽象迭代器接口
class Iterator
{
public:
virtual bool hasNext() = 0;
virtual int next() = 0;
};
// 集合类接口
class Aggregate
{
public:
virtual Iterator *createIterator() = 0;
virtual void addItem(int item) = 0;
virtual int getItem(int index) = 0; // 添加getItem()方法
virtual int getSize() = 0; // 添加getSize()方法
};
// 具体迭代器类
class ConcreteIterator : public Iterator
{
private:
Aggregate *aggregate;
int position;
public:
ConcreteIterator(Aggregate *a) : aggregate(a), position(0) {}
bool hasNext() override
{
return position < aggregate->getSize();
}
int next() override
{
int item = aggregate->getItem(position);
position++;
return item;
}
};
// 具体集合类
class ConcreteAggregate : public Aggregate
{
private:
std::vector<int> items;
public:
Iterator *createIterator() override
{
return new ConcreteIterator(this);
}
void addItem(int item) override
{
items.push_back(item);
}
int getItem(int index) override
{
// 实现getItem()方法
return items[index];
}
int getSize() override
{
// 实现getSize()方法
return items.size();
}
};
int main()
{
ConcreteAggregate aggregate;
aggregate.addItem(1);
aggregate.addItem(3);
aggregate.addItem(2);
Iterator *iterator = aggregate.createIterator();
while (iterator->hasNext())
{
int item = iterator->next();
// 处理每个元素
std::cout << item << "\n";
}
delete iterator;
return 0;
}
运行结果:
1
3
2