//迭代器模式
//提供一种方法,顺序遍历一个聚合对象中的各个元素,而又不暴露该对象的内部表示
//提供 开始、下一个、是否结束、当前对象 等常规接口
#include <iostream>
using namespace std;
//定义了抽象类作为接口
//抽象迭代器
template<class Item>
class Iterator
{
public:
virtual void first() = 0;
virtual void next() = 0;
virtual Item* currentItem() = 0;
virtual bool isDone() = 0;
virtual ~Iterator() {}
};
//抽象聚集
template<class Item>
class Aggregate
{
public:
virtual Iterator<Item>* createIterator() = 0;
virtual ~Aggregate() {}
};
//用DoubleList和ListIterator继承接口
template<class DataType>
class DoubleList;
template<class DataType>
class ListIterator : public Iterator <DataType>
{
DoubleList<DataType> * aggr;
int cur;
public:
ListIterator(DoubleList<DataType>* a)
:aggr(a), cur(0)
{}
virtual void first()
{
cur = 0;
}
virtual void next()
{
if (cur<aggr->getLen())
cur++;
}
virtual DataType* currentItem()
{
if (cur < aggr->getLen())
return &(aggr->getData(cur));
else
return nullptr;
}
virtual bool isDone()
{
return (cur >= aggr->getLen());
}
};
template<typename DataType>
class DoubleList :public Aggregate<DataType> {
private:
struct Node {
DataType data;
Node * ptrNext;
Node * ptrPrev;
Node(const DataType & d = DataType{}, Node * next = nullptr, Node * prev = nullptr) :
data(d), ptrNext(next), ptrPrev(prev)
{}
};
private:
int theSize;
Node * head;
Node * tail;
public:
DoubleList() {
theSize = 0;
head = new Node;
tail = new Node;
head->ptrNext = tail;
tail->ptrPrev = head;
}
~DoubleList() {
clear();
delete head;
delete tail;
}
private:
Node * position(int index) {
Node * ptr = head->ptrNext;
for (int i = 0; i < index; ++i) {
ptr = ptr->ptrNext;
}
return ptr;
}
public:
virtual Iterator<DataType>* createIterator()
{
return new ListIterator<DataType>(this);
}
DataType& getData(int index) {
Node * n = position(index);
return n->data;
}
void insert(int pos, const DataType & d) {
++theSize;
Node* temp = new Node;
temp->data = d;
Node* cur = position(pos);
temp->ptrNext = cur;
temp->ptrPrev = cur->ptrPrev;
cur->ptrPrev = temp;
temp->ptrPrev->ptrNext = temp;
}
void erase(int pos) {
Node * temp = position(pos);
temp->ptrNext->ptrPrev = temp->ptrPrev;
temp->ptrPrev->ptrNext = temp->ptrNext;
delete temp;
}
int getLen()
{
return theSize;
}
void show() {
cout << "size: " << theSize << endl;
for (Node * ptr = head->ptrNext; ptr->ptrNext != nullptr; ptr = ptr->ptrNext)
cout << ptr->data << " ";
cout << endl;
}
void clear() {
while (head->ptrNext != tail) {
erase(0);
}
}
};
//迭代器模式
cout << endl << "迭代器模式" << endl;
DoubleList<int> li;
li.insert(0, 1);
li.insert(0, 2);
li.insert(0, 3);
li.show();
Iterator<int> *it = li.createIterator();
for (it->first(); !it->isDone(); it->next())
{
cout << *(it->currentItem()) << endl;
}
delete it;