本文共 2716 字,大约阅读时间需要 9 分钟。
迭代器模式(Iterator Pattern)是一种行为设计模式,旨在将对容器中包含的内部对象的访问委托给外部类,并通过Iterator(遍历器)按顺序进行访问。这种模式能够有效地处理按顺序遍历聚集对象集合的需求。
迭代器模式的核心目标是提供一种高效且安全的方式来遍历容器中的元素。传统的实现方式可能面临以下问题:
迭代器模式通过引入专门的遍历器接口,解耦了遍历逻辑和容器的实现细节。它适用于以下场景:
迭代器模式的主要角色包括:
hasNext()、next()等。通过这种方式,遍历器可以通过持有容器的引用来访问容器中的元素,而无需直接暴露容器的内部结构。
以下是一个使用迭代器模式的典型案例:
#include#include using namespace std;typedef int Object;class MyIterator {public: virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() = 0; virtual Object CurrentItem() = 0;};class Aggregate {public: virtual Object getItem(int index) = 0; virtual MyIterator* CreateIterator() = 0; virtual int GetSize() = 0;};class ConcreteIterator : public MyIterator {public: ConcreteIterator(Aggregate* aggregate) { _aggregate = aggregate; _currentIndex = 0; } ~ConcreteIterator() { _aggregate = NULL; _currentIndex = 0; } virtual void First() { _currentIndex = 0; } virtual void Next() { if (_currentIndex < _aggregate->GetSize()) { _currentIndex++; } } virtual bool IsDone() { return _currentIndex == _aggregate->GetSize(); } virtual Object CurrentItem() { return _aggregate->getItem(_currentIndex); }protected:private: int _currentIndex; Aggregate* _aggregate;};class ConcreteAggregate : public Aggregate {public: ConcreteAggregate(int size) { for (int i = 0; i < size; i++) { _objects[i] = "Object" + (i + 1); } } ~ConcreteAggregate() { delete[] _objects; } virtual Object getItem(int index) { return _objects[index]; } virtual MyIterator* CreateIterator() { return new ConcreteIterator(this); } virtual int GetSize() { return _size; }protected:private: Object* _objects; int _size;};void main() { // 创建一个容器 ConcreteAggregate* aggregate = new ConcreteAggregate(5); // 创建一个遍历器 MyIterator* iterator = aggregate->CreateIterator(); // 遍历容器中的元素 while (!iterator->IsDone()) { Object currentItem = iterator->CurrentItem(); cout << currentItem << " "; iterator->Next(); } // 释放资源 delete iterator; delete aggregate;}
迭代器模式通过引入遍历器接口,成功地将遍历逻辑与容器的实现细节解耦。这种模式不仅提高了代码的可维护性和扩展性,还为容器的其他操作提供了更干净的接口。通过合理使用迭代器模式,可以在保证安全性的前提下,简化对容器内部结构的访问,充分发挥容器与遍历器之间的依赖关系。
转载地址:http://gaur.baihongyu.com/