设计模式

iterator模式

2017-11-23  本文已影响0人  老练子丶2017

类似于stl里面的迭代器

iterator.h

#ifndef _ITERATOR_H

#define _ITERATOR_H

#include <iostream>

#include <vector>

using namespace std;

template <class item>

class Iterator

{

public:

virtual ~Iterator() {}

virtual void first()=0;

virtual void next()=0;

virtual item* currentItem()=0;

virtual bool isDone()=0;

};

template <class item>

{

public:

virtual ~Aggregate() {}

virtual Iterator*<item> createIterator()=0;

virtual void pushData(item)=0;

};

template <class item>

class ConcreteIterator;

template<class item>

class ConcreteAggregate : public Aggregate<item>

{

public: ConcreteAggregate() { }

int getLen() { return data.size(); }

void pushData(item a) { data.push_back(a); }

item& operator[](int index) { return data[index]; }

Iterator<item>* createIterator() { return new ConcreteIterator<item>(this); }

private:

vector<item> data;

};

template<class item>

class ConcreteIterator : public Iterator<item>

{

public:

ConcreteIterator(ConcreteAggregate<item>* a) : aggr_(a), cur_(0) {}

void first() { cur_ = 0; }

void next() { if (cur_ < aggr_->getLen()) { cur_ ++; } }

bool isDone() { return (cur_ >= aggr_->getLen()); }

item* currentItem() { if (cur_ < aggr_->getLen()) { return &(*aggr_)[cur_]; } else { return NULL; } }

private:

int cur_;

ConcreteAggregate<item>* aggr_;

}

#endif // _ITERATOR_H

iterator.cpp

#include "iterator.h"

int main()

 Aggregate<int>* aggr = new ConcreteAggregate<int>(); 

 aggr->pushData(1); 

 aggr->pushData(2); 

 aggr->pushData(3); 

 Iterator<int>* it = aggr->createIterator();

for (it->first(); !it->isDone(); it->next()) {

cout << *(it->currentItem())  << endl;

}

return 0;

}

编译:make iterator

上一篇下一篇

猜你喜欢

热点阅读