迭代器模式(Iterator)提供一种方法可以访问聚合对象,而不用暴露这个对象的内部表示。结构图为:
我们实现一个存储INT的栈结构,用迭器来访问这个结构中的数据,结构图为:
实现代码:
//IntStack.h
class IntStack
{
public:
IntStack();
virtual ~IntStack();
void Push(int);
int Pop();
friend class IntStackIterator;
private:
enum { SIZE = 100 };
int m_nStack[SIZE];
int m_nTop;
};
//IntStack.cpp
#include "stdafx.h"
#include "IntStack.h"
#include <iostream>
using namespace std;
IntStack::IntStack()
{
m_nTop = 0;
}
IntStack::~IntStack()
{
}
void IntStack::Push(int nData)
{
if(m_nTop < SIZE)
{
m_nStack[m_nTop++] = nData;
}
else
{
cout << "超出容量范围。" << endl;
}
}
int IntStack::Pop()
{
if(m_nTop > 0)
{
return m_nStack[--m_nTop];
}
return 0;
}
//Iterator.h
class Iterator
{
public:
Iterator();
virtual ~Iterator();
virtual int operator++() = 0;
virtual int operator++(int) = 0;
};
//Iterator.cpp
#include "stdafx.h"
#include "Iterator.h"
Iterator::Iterator()
{
}
Iterator::~Iterator()
{
}
//IntStack.h
#include "Iterator.h"
class IntStack;
class IntStackIterator : public Iterator
{
public:
IntStackIterator(IntStack*);
virtual ~IntStackIterator();
int operator++();
int operator++(int);
private:
IntStack* m_pStack;
int m_nIndex;
};
//IntStackIterator.cpp
#include "stdafx.h"
#include "IntStackIterator.h"
#include "IntStack.h"
IntStackIterator::IntStackIterator(IntStack* pStack)
{
m_pStack = pStack;
m_nIndex = 0;
}
IntStackIterator::~IntStackIterator()
{
if(m_pStack != NULL)
{
delete m_pStack;
m_pStack = NULL;
}
}
int IntStackIterator::operator++()
{
if(m_nIndex < m_pStack->m_nTop)
{
return m_pStack->m_nStack[++m_nIndex];
}
return 0;
}
int IntStackIterator::operator++(int)
{
if(m_nIndex < m_pStack->m_nTop)
{
return m_pStack->m_nStack[m_nIndex++];
}
return 0;
}
//main.cpp
#include "stdafx.h"
#include "Iterator.h"
#include "IntStackIterator.h"
#include "IntStack.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
IntStack* pStack = new IntStack;
for(int i = 0; i < 20; ++i)
{
pStack->Push(i);
}
Iterator* pIt = new IntStackIterator(pStack);
for(i = 0; i < 20; ++i)
{
cout << (*pIt)++ << endl;
}
return 0;
}