首页 > 代码库 > Iterator模式(C++迭代器模式)

Iterator模式(C++迭代器模式)

基本上来说,Iterator模式并没有什么可多说得,在STL中见得实在太多了,一般用于遍历数据结构,其实现也相对简单。

 

 代码如下:

//////////////////////////////////////////////////////////////////////////
// author: Jeson Yang
//date:2014.12.10
//file:main.cpp
//////////////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std;
class Interator;
class Aggregate
{
public:
	virtual ~Aggregate(){}
	virtual Interator* CreateItrator()=0{};
	virtual int GetSize()=0{}
	virtual int GetItem(int index)=0{}
protected:
	Aggregate(){}
};


class ConcreteAggregate:public Aggregate
{
public:
	enum{size=3};
	ConcreteAggregate()
	{
		for(int i=0;i < size;i++)
			m_obj[i]=i;
	}
	~ConcreteAggregate(){}
	Interator* CreateItrator();
	int GetItem(int index)
	{
		if(GetSize()) return m_obj[index];
		else return -1;
	}
	int GetSize(){return size;}
private:
	int m_obj[size];
};


class Interator
{
public:
	virtual ~Interator(){};
	virtual void First()=0;
	virtual void Next()=0;
	virtual bool IsDone()=0;
	virtual int CurrentItem()=0;
protected:
	Interator(){}
};


class ConcreteInterator:public Interator
{
public:
	ConcreteInterator(Aggregate* ag,int index=0)
	{m_ag=ag;m_index=index;}
	~ConcreteInterator(){}
	void First(){m_index=0;}
	void Next()
	{
		if(m_index != m_ag->GetSize()) m_index++;
	}
	bool IsDone(){return(m_index==m_ag->GetSize());}
	int CurrentItem(){return m_ag->GetItem(m_index);}
private:
	Aggregate* m_ag;
	int m_index;
};


Interator* ConcreteAggregate::CreateItrator()
{
	return new ConcreteInterator(this);
}


void main()
{
	Aggregate* ag=new ConcreteAggregate();
	Interator* it=new ConcreteInterator(ag);
	for(;!(it->IsDone());it->Next())
	{
		cout<<it->CurrentItem()<<endl;
	}

	delete it;
	delete ag;
}


 

Iterator模式(C++迭代器模式)