[设计模式]Iterator迭代器模式

问题

iterator模式应该是最为熟悉的模式了,最简单的证明就是在实现Composite模式,Flyweight模式,Observer模式中就直接用到了STL提供的Iterator来遍历Vector或者List数据结构。

Iterator模式也正是用来解决对一个聚合对象的遍历问题,将对聚合的遍历封装到一个类中进行,这样就避免了暴露这个聚合对象的内部表示的可能。

iterator迭代器模式

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

[设计模式]Iterator迭代器模式_第1张图片

小demo

iterator.h

#ifndef ITERATOR_H
#define ITERATOR_H

typedef int DATA;
class Iterater;
// 容器的抽象基类
class Aggregate
{
public:
	virtual ~Aggregate(){}
	virtual Iterater* CreateIterater(Aggregate *pAggregate) = 0;
	virtual int GetSize() = 0;
	virtual DATA GetItem(int nIndex) = 0;
};

// 迭代器的抽象基类
class Iterater
{
public:
	virtual ~Iterater(){}

	virtual void First()		= 0;
	virtual void Next()			= 0;
	virtual bool IsDone()		= 0;
	virtual DATA CurrentItem()	= 0; 
};

// 一个具体的容器类,这里是用数组表示
class ConcreateAggregate	: public Aggregate
{
public:
	ConcreateAggregate(int nSize);
	virtual ~ConcreateAggregate();
	virtual Iterater* CreateIterater(Aggregate *pAggregate);
	virtual int GetSize();
	virtual DATA GetItem(int nIndex);
private:
	int m_nSize;
	DATA *m_pData;
};

// 访问ConcreateAggregate容器类的迭代器类
class ConcreateIterater : public Iterater
{
public:
	ConcreateIterater(Aggregate* pAggregate);
	virtual ~ConcreateIterater(){}

	virtual void First();
	virtual void Next();
	virtual bool IsDone();
	virtual DATA CurrentItem();
private:
	Aggregate  *m_pConcreateAggregate;
	int			m_nIndex;
};

#endif

 

iterator.cpp

#include <iostream>
#include "Iterator.h"

ConcreateAggregate::ConcreateAggregate(int nSize) : m_nSize(nSize), m_pData(NULL)
{
	m_pData = new DATA[m_nSize];
	
	for (int i = 0; i < nSize; ++i)
	{
		m_pData[i] = i;
	}
}

ConcreateAggregate::~ConcreateAggregate()
{
	delete [] m_pData;
	m_pData = NULL;
}

Iterater* ConcreateAggregate::CreateIterater(Aggregate *pAggregate)
{
	return new ConcreateIterater(this);
}

int ConcreateAggregate::GetSize()
{
	return m_nSize;
}

 

main.cpp

#include "Iterator.h"
#include <iostream>

int main()
{
	Aggregate* pAggregate = new ConcreateAggregate(4);
	Iterater*  pIterater  = new ConcreateIterater(pAggregate);

	for (; false == pIterater->IsDone(); pIterater->Next())
	{
		std::cout << pIterater->CurrentItem() << std::endl;
	}
    system("pause");
	return 0;
}

 

你可能感兴趣的:([设计模式]Iterator迭代器模式)