#include <iostream>
using namespace std;
typedef int Object;
#define SIZE 5
class MyIterator
{
public:
virtual void next() = 0;
virtual Object CurrentItem() = 0;
virtual bool isDone() = 0;
};
class Aggreate
{
public:
virtual int getSize() = 0;
virtual MyIterator *CreatIterator() = 0;
virtual Object getItem(int index) = 0;
};
class ConcreteIterator :public MyIterator
{
public:
ConcreteIterator(Aggreate*aggreate)
{
m_aggreate = aggreate;
current_index = 0;
}
virtual void next()
{
current_index++;
}
virtual Object CurrentItem()
{
return m_aggreate->getItem(current_index);
}
virtual bool isDone()
{
return current_index == m_aggreate->getSize();
}
private:
int current_index;
Aggreate *m_aggreate;
};
class ConcreteAggreate :public Aggreate
{
public:
ConcreteAggreate()
{
for (int i = 0; i < SIZE; i++)
{
object[i] = i + 100;
}
}
virtual int getSize()
{
return SIZE;
}
virtual MyIterator *CreatIterator()
{
return new ConcreteIterator(this);
}
virtual Object getItem(int index)
{
return object[index];
}
private:
Object object[5];
};
void main()
{
ConcreteAggreate *obj = new ConcreteAggreate;
ConcreteIterator *it = new ConcreteIterator(obj);
for (; !(it->isDone()); it->next())
{
cout << it->CurrentItem() << " ";
}
delete it;
delete obj;
}
运行结果: