设计模式——迭代器模式||c++详解

目录

 

1.什么是迭代器模式?

2.迭代器模式的设计

3.迭代器模式的实现


1.什么是迭代器模式?

迭代器模式就是提供一种方法,去访问一个聚合对象内的各个元素,同时又不暴露该对象的内部结构。

相当于c++11提供的foreach语句。因此迭代器模式也是非常简单的,只是给对象加了遍历的功能而已。如果说我们将一个数组当作一个对象,那么带有能遍历数组功能的方法的类其实就是符合迭代器模式的,STL容器里面带有迭代器的顺序容器和关联容器其实都是符合迭代器模式的设计规范的。

2.迭代器模式的设计

由于迭代器会按照顺序去访问对象内的各个元素,所以它包括具有以下几功能的接口:

  1. 得到下一个元素
  2. 是否到达结尾
  3. 得到需要遍历的对象

迭代器的实现:

class Iterator
{
public:
	virtual T& Next() = 0;
	virtual bool IsEnd() = 0;
};

上面是迭代器的基类。

由于每个对象的结构可能不同,我们可以将每个对象的迭代器封装在对象的内部。

3.迭代器模式的实现

# include<iostream>
using namespace std;
# include<vector>
template<typename T>
//基类
class Iterator
{
public:
	virtual T& Next() = 0;
	virtual bool IsEnd() = 0;
};

template<typename T>
class Arry
{
public:
	//内部迭代器
	template<typename T>
	class TIterator :public Iterator<T>
	{
	public:
		//获取对象
		TIterator(Arry<T>& arry) :obj(arry)
		{
			curIndex = 0;
		}
		//下一个元素
		T& Next()
		{
			if (!IsEnd())
			{

				return obj.arry[curIndex++];
			}
		}
		//判断是否到达结尾
		 bool IsEnd()
		 {
			 return curIndex>= obj.arry.size();
		 }
	private:
		int curIndex;
		Arry<T>& obj;

	};
	void Push(T value)
	{
		arry.push_back(value);
	}
	//创建迭代器
	Iterator<T>* CreateIte()
	{
		return new TIterator<T>(*this);
	}
private:
	vector<T> arry;

};
int main()
{
	Arry<int> arry;
	arry.Push(1);
	arry.Push(2);
	arry.Push(3);
	arry.Push(4);
	Iterator<int>* it = arry.CreateIte();
	while(!it->IsEnd())
	{
		cout << it->Next() << endl;
	}
	delete it;

	return 0;
}

程序运行结果如下所示:

发布了124 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42214953/article/details/105427278