設計模式(二十一)迭代器模式

意圖:提供一種方法順序訪問一個聚合對象中各個元素, 而又無須暴露該對象的內部表示。

當需要訪問一個聚集對象,且不論這個對象是什麼都需要遍歷的時候就應該考慮迭代器模式

#include <iostream>
using namespace std;
typedef int Object;
#define SIZE 5 

class MyIterator
{
public:
	virtual void First() = 0;
	virtual void Next() = 0;
	virtual bool IsDone() = 0;
	virtual Object CurrentItem() = 0;
};

class Aggregate
{
public:
	virtual MyIterator *CreateIterator() = 0;
	virtual Object getItem(int index) = 0;
	virtual int getSize() = 0;
};

class ContreteIterator : public MyIterator
{
public:
	ContreteIterator(Aggregate *ag)
	{
		_ag = ag;
		_current_index = 0;
	}

	virtual void First()
	{
		_current_index = 0;  //讓當前 遊標 回到位置0
	}

	virtual void Next()
	{
		if (_current_index < _ag->getSize())
		{
			_current_index++;
		}
	}

	virtual bool IsDone()
	{
		return  (_current_index == _ag->getSize());
	}

	virtual Object CurrentItem()
	{
		return _ag->getItem(_current_index);
	}
private:
	int            _current_index;
	Aggregate    *_ag;
};

class ConcreteAggregate : public Aggregate
{
public:
	ConcreteAggregate()
	{
		for (int i = 0; i < SIZE; i++)
		{
			object[i] = i + 100;
		}
	}

	virtual MyIterator *CreateIterator()
	{
		return new ContreteIterator(this); //讓迭代器 持有一個 集合的 引用 
	}

	virtual Object getItem(int index)
	{
		return object[index];
	}

	virtual int getSize()
	{
		return SIZE;
	}
private:
	Object object[SIZE];
};

void main()
{
	Aggregate * ag = new ConcreteAggregate;

	MyIterator *it = ag->CreateIterator();

	for (; !(it->IsDone()); it->Next())
	{
		cout << it->CurrentItem() << " ";
	}

	delete it;
	delete ag;

	system("pause");
	return;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章