C++实现迭代器模式
版权声明:本文为博主原创文章,未经博主允许不得转载。
说实话这个迭代器模式实现起来有点模糊
- /*
- 迭代器模式:提供一种方法顺序访问一个聚合对象中个各个元素,而不暴露该对像的内部表示.
- 模式的动机:
- (1)一个聚合对象,如一个列表(List)或者一个集合(Set),应该提供一种方法来让别人可以访问
- 它的元素,而又不需要暴露它的内部结构。
- (2)针对不同的需要,可能还要以不同的方式遍历整个聚合对象,但是我们并不希望在聚合对象的
- 抽象层接口中充斥着各种不同遍历的操作。
- (3)怎样遍历一个聚合对象,又不需要了解聚合对象的内部结构,还能够提供多种不同的遍历方式,
- 这就是迭代器模式所要解决的问题。
- Created by Phoenix_FuliMa
- */
- #include <iostream>
- #include <vector>
- using namespace std;
- /* object可以是任意类型的变量 */
- typedef int object;
- class Iterator
- {
- public:
- virtual object begin() = 0;
- virtual void next() = 0;
- virtual object end() = 0;
- virtual object current() = 0;
- virtual bool IsDone() = 0;
- };
- class ConcreteAggregate
- {
- private:
- vector<object> _objects;
- public:
- void AddObject(object obj)
- {
- _objects.push_back(obj);
- }
- object& operator[](int index)
- {
- return _objects[index];
- }
- int size()
- {
- return _objects.size();
- }
- };
- class ConcreteIterator:public Iterator
- {
- public:
- ConcreteAggregate *agg;
- int _index;
- public:
- ConcreteIterator(ConcreteAggregate *agg)
- {
- this->agg = agg;
- _index = 0;
- }
- virtual object begin()
- {
- return (*agg)[0];
- }
- virtual void next()
- {
- _index++;
- }
- virtual object end()
- {
- _index = agg->size();
- return (*agg)[_index];
- }
- virtual object current()
- {
- return (*agg)[_index];
- }
- virtual bool IsDone()
- {
- return (_index == agg->size());
- }
- };
- int main()
- {
- ConcreteAggregate *objects =new ConcreteAggregate();
- object a = 1;
- object b = 2;
- object c = 3;
- objects->AddObject(a);
- objects->AddObject(b);
- objects->AddObject(c);
- ConcreteIterator *iter = new ConcreteIterator(objects);
- object tmp_begin = iter->begin();
- while(!iter->IsDone())
- {
- cout<<iter->current()<<" ";
- iter->next();
- }
- cout<<endl;
- delete objects;
- delete iter;
- system("pause");
- return 0;
- }