Iterator(迭代器)模式

来源:互联网 发布:akb48少女时代知乎 编辑:程序博客网 时间:2024/04/30 12:08

一、迭代器模式简介(Brief Introduction)

迭代器模式(Iterator Pattern),提供一种方法顺序访问一个聚合对象中元素,而不暴露改集合对象的内部表示

二、解决的问题(What To Solve)

当需要访问一个聚集对象,而且不管这些对象是什么都需要遍历的时候,应该考虑用迭代器模式;当需要对聚集有多种方式遍历时,可以考虑使用迭代器模式

三、迭代器模式分析(Analysis)

Iterator迭代器接口,定义访问和遍历元素的接口
ConcreteIterator:具体的迭代器实现对象,实现对聚合对象的遍历,并跟踪遍历时的当前位置
Aggregate:聚合对象,定义创建相应迭代器对象的接口
ConcreteAggregate:具体聚合对象,实现创建相应的迭代器对象

四、源代码

1、List被迭代对象

template <class Item> class List2{public:List2():_index(0){}int count() const{return _index;}void add(Item i){_item[_index] = i;_index ++;}Item& get(int index){return _item[index];}private:Item _item[DEFAULT_LIST_SIZE];int _index;};

2、Iterator迭代器

template <class Item>class Iterator2{public:virtual void begin() = 0;virtual void next() = 0;virtual bool isDone() const = 0;virtual Item& currItem() const = 0;};
template <class Item> class ConcreteIterator:public Iterator2<Item>{public:ConcreteIterator(List2<Item> *list):_list(list),_curr(0){}virtual void begin(){_curr = 0;}virtual void next(){++_curr;}virtual bool isDone() const{if (_curr > _list->count()){return true;}return false;}virtual Item& currItem() const{return _list->get(_curr);}private:List2<Item> *_list;int _curr;};

3、Aggregate聚合对象

template <class Item>class Aggregate{public:virtual Iterator2<Item>* createIterator() = 0;};
template <class Item>class ConcreteAggregate:public Aggregate<Item>{public:ConcreteAggregate(List2<Item> *list):_list(list){}virtual Iterator2<Item>* createIterator(){return new ConcreteIterator<Item>(_list);}private:List2<Item> *_list;};

4、Client代码

int main(){    List2<string> *list = new List2<string>();;list->add("hello");list->add("world");Iterator2<string> *iter = (new ConcreteAggregate<string>(list))->createIterator();iter->begin();while(!iter->isDone()){std::cout << iter->currItem() << std::endl;iter->next();}return 0;}
原创粉丝点击