您的位置:首页 > 其它

设计模式:20 想走?可以!先买票_迭代器模式

2015-08-13 14:16 405 查看
迭代器模式:

含义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部

何时使用:当你需要访问一个聚集对象,而且不管这些对象是什么都需要遍历的时候,应该考虑使用迭代器模式。你需要对聚集有多种方式遍历时,可以考虑使用迭代器模式。为遍历不同的聚集结构提供如:开始、下一个、是否结束、当前哪一项等统一的接口。



迭代器角色:Iterator,负责定义访问和遍历元素的接口

具体迭代器角色:Concrete Iterator,要实现迭代器接口,并记录遍历中的当前位置

集合角色:Aggregate,负责提供创建具体迭代角色的接口

具体集合角色:Concrete Aggregate,实现创建具体迭代器角色的接口—---这个具体迭代器角色与该集合的结构相关。



实现要点:

迭代抽象:访问一个聚合对象内容而无须暴露它的内部表示

迭代多态:为便利不同集合结构提供统一接口,从而支持同样的算法在不同的集合结构上进行操作



main.cpp

#include <iostream>
#include <stdlib.h>
#include "Aggregate.h"
#include "ConcreteAggregate.h"
#include "Iterator.h"
#include "ConcreteIterator.h"
using namespace std;

void process()
{
	Aggregate<int>* aggr = new ConcreteAggregate<int>();
	Iterator<int>* it = aggr->createIterator();
	for(it->first() ; !it->isDone() ; it->next())
	{
		cout << *(it->currentItem()) << endl;
	}
	delete it;
	delete aggr;
}

int main(int argc,char* argv[])
{
	process();
	system("pause");
	return 0;
}


Aggregate.h

#ifndef AGGREGATE_H
#define AGGREGATE_H
#include "Iterator.h"
template<typename Item>
class Aggregate
{
public:
	Aggregate(void){}
	virtual ~Aggregate(void){}
	//由集合角色创建迭代器
	virtual Iterator<Item>* createIterator() = 0;
};
#endif


ConcreteAggregate.h

#ifndef CONCRETEAGGREGATE_H
#define CONCRETEAGGREGATE_H
#include "aggregate.h"
#include <vector>

//具体集合角色,用于创建迭代器接口
template<typename Item>
class ConcreteAggregate :
	public Aggregate<Item>
{
public:
	ConcreteAggregate()
	{
		_vecData.push_back(1);
		_vecData.push_back(2);
		_vecData.push_back(3);
	}
	~ConcreteAggregate(void)
	{
	}
	virtual Iterator<Item>* createIterator()
	{
		//?内存泄露
		return new ConcreteIterator<Item>(this);
	}
	Item& operator[](int index)
	{
		return _vecData.at(index);
	}
	int getLen()
	{
		return _vecData.size();
	}
private:
	std::vector<Item> _vecData;
};
#endif


Iterator.h

#ifndef ITERATOR_H
#define ITERATOR_H

//注意,有模板的尽量将声明和实现放在一个文件中
template<typename Item>
class Iterator
{
public:
	Iterator(void){}
	virtual ~Iterator(void){}
	virtual void first() = 0;
	virtual void next() = 0;
	virtual Item* currentItem() = 0;
	virtual bool isDone() = 0;
};
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: