行为型模式之迭代器模式

#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;
}

运行结果:


阅读更多
上一篇行为型模式之解释器模式
下一篇数据结构之空间换时间
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭