意图:
提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Iterator
AbstractList
#include "Iterator.h"
namespace NS_ITERATOR {
template <class Item>
class AbstractList {
public:
AbstractList() {}
virtual ~AbstractList() {}
virtual long getCount(void) const = 0;
virtual Item getItem(long index) const = 0;
virtual Iterator<Item> *createIterator(void) const = 0;
};
} /* namespace NS_ITERATOR */
List
#include "AbstractList.h"
#include "ListIterator.h"
namespace NS_ITERATOR {
template <class Item>
class List : public AbstractList<Item> {
public:
List()
{
for (int i = 0; i < 10; i++)
_items[i] = i;
}
virtual ~List() {}
virtual long getCount(void) const;
virtual Item getItem(long index) const;
virtual Iterator<Item> *createIterator(void) const;
private:
Item _items[10];
};
template <class Item>
long List<Item>::getCount(void) const {
return 10;
}
template <class Item>
Item List<Item>::getItem(long index) const {
return _items[index];
}
template <class Item>
Iterator<Item> *List<Item>::createIterator(void) const {
return new ListIterator<Item>(this);
}
} /* namespace NS_ITERATOR */
Iterator
namespace NS_ITERATOR {
template <class Item>
class Iterator {
public:
Iterator() {}
virtual ~Iterator() {}
virtual void first(void) = 0;
virtual void next(void) = 0;
virtual bool isDone(void) const = 0;
virtual Item currentItem(void) const = 0;
};
} /* namespace NS_ITERATOR */
ListIterator
#include "Iterator.h"
#include "AbstractList.h"
namespace NS_ITERATOR {
template <class Item>
class ListIterator : public Iterator<Item> {
public:
ListIterator(const AbstractList<Item> *aList);
virtual ~ListIterator() {}
virtual void first(void);
virtual void next(void);
virtual bool isDone(void) const;
virtual Item currentItem(void) const;
private:
const AbstractList<Item> *_list;
long _current;
};
template <class Item>
ListIterator<Item>::ListIterator(const AbstractList<Item> *aList) : _list(aList), _current(0) {}
template <class Item>
void ListIterator<Item>::first(void) {
_current = 0;
}
template <class Item>
void ListIterator<Item>::next(void) {
_current++;
}
template <class Item>
bool ListIterator<Item>::isDone(void) const {
return _current >= _list->getCount();
}
template <class Item>
Item ListIterator<Item>::currentItem(void) const {
return _list->getItem(_current);
}
} /* namespace NS_ITERATOR */
IteratorPtr
#include "Iterator.h"
namespace NS_ITERATOR {
template <class Item>
class IteratorPtr {
public:
IteratorPtr(Iterator<Item> *i) : _i(i) {}
virtual ~IteratorPtr() { delete _i; }
Iterator<Item> *operator->() { return _i; }
private:
Iterator<Item> *_i;
};
} /* namespace NS_ITERATOR */
main
#include <iostream>
#include "Iterator/List.h"
#include "Iterator/ListIterator.h"
#include "Iterator/IteratorPtr.h"
using namespace NS_ITERATOR;
int main(void)
{
List<int> lt;
IteratorPtr<int> li(lt.createIterator());
for (li->first(); !li->isDone(); li->next())
std::cout << li->currentItem() << std::endl;
}
附加: