23种设计模式之迭代器模式(行为型,11 Iterator,c++实现)

23种设计模式之迭代器模式(行为型,11 Iterator,c++实现)

23种设计模式之迭代器模式(行为型,11 Iterator,c++实现)

23种设计模式之迭代器模式(行为型,11 Iterator,c++实现)

代码实现:

#include <iostream>


using namespace std;


typedef int Object;

#define SIZE 5


class Iterator {

public:

virtual void first() = 0;

virtual void next() = 0;

virtual bool hasNext() = 0;

virtual Object getCurrentItem() = 0;

};


class Aggregate

{

public:

virtual Iterator* createIterator() = 0;

virtual int getSize() = 0;

virtual Object getItem(int index) = 0;

};


class ConcreteIterator :public Iterator 

{

public:

ConcreteIterator(Aggregate* agg)

{

this->agg = agg;

first();

}

virtual void first()

{

index = 0;

}

virtual void next() 

{

if (index < agg->getSize())

{

index++;

}

}

virtual bool hasNext()

{

return index < agg->getSize() ? true : false;

}

virtual Object getCurrentItem()

{

return agg->getItem(index);

}

private:

int index;

Aggregate* agg;

};


class ConcreteAggregate :public Aggregate

{

public:

ConcreteAggregate()

{

for (int i = 0; i < SIZE; i++)

{

objects[i] = i;

}

}

virtual Iterator* createIterator()

{

return new ConcreteIterator(this);

}

virtual int getSize()

{

return SIZE;

}

virtual Object getItem(int index)

{

return objects[index];

}

private:

Object objects[SIZE];

};


void main()

{

Aggregate* agg = new ConcreteAggregate;

Iterator* it = agg->createIterator();

for (; it->hasNext(); it->next())

{

cout << it->getCurrentItem() << endl;

}


delete agg;

delete it;

}