迭代器模式

GOOD:提供一种方法顺序访问一个聚敛对象的各个元素,而又不暴露该对象的内部表示。

为遍历不同的聚集结构提供如开始,下一个,是否结束,当前一项等统一接口。


#include <iostream>
using namespace std;

// MyIterator  Aggregate ContreteIterator ConcreteAggregate

//	a	 b	c	d
//      ▲


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);
	}
protected:
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值