一、应用场景
- 访问一个聚合对象的内容而无需暴露它的内部表示。
- 支持对聚合对象的多种遍历
- 为遍历不同的聚合结构提供一个
统一的接口
(即支持多态迭代)
二、通用类图

- ConcreteAggregate:具体的集合对象类
- ConcreteIterator:迭代器对象
三、实现
3.1 类图
- 以电视机和遥控器为场景进行设计

3.2 代码实现
#include <iostream>
#include <vector>class Item;class Iterator
{
public:virtual Item* first() = 0;virtual Item* next() = 0;virtual bool isDone() = 0;virtual Item* currentItem() = 0;
};class Item
{
private:std::string name;public:Item(const std::string& name){this->name = name;}std::string getName(){return name;}
};class ITelevision
{
public:virtual Iterator* createIterator() = 0;virtual std::vector<Item*> getChannel() = 0;
};class Controller : public Iterator
{
private:unsigned int current = 0;std::vector<Item*> channel;public:Controller(std::vector<Item*> channel){this->channel = channel;}Item* first(){return channel[0];}Item* next(){current++;return channel[current];}Item* currentItem(){return channel[current];}bool isDone(){return current >= channel.size() - 1;}
};class HaierTV : public ITelevision
{
private:std::vector<Item*> channel;public:HaierTV(){channel.push_back(new Item("channel 1"));channel.push_back(new Item("channel 2"));channel.push_back(new Item("channel 3"));channel.push_back(new Item("channel 4"));channel.push_back(new Item("channel 5"));channel.push_back(new Item("channel 6"));channel.push_back(new Item("channel 7"));}std::vector<Item*> getChannel(){return channel;}Iterator* createIterator(){return new Controller(channel);}};
int main()
{ITelevision* tv = new HaierTV();Iterator* it = tv->createIterator();std::cout << it->first()->getName() << std::endl;while (!it->isDone()) {std::cout << it->next()->getName() << std::endl;}return 0;
}