【代码片-1】 设计模式学习笔记--迭代器模式

浏览: 146 发布日期: 2016-11-27 分类: c++
// Design Pattern.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;


//迭代器基类
class Iterator
{
public:
	//迭代器向后指向一个
	virtual void Next() = 0;
	//迭代器指向首元素
	virtual void Begin() = 0;
	//迭代器是否指向容器末尾
	virtual bool IsEnd() = 0;
	//返回当前迭代器所指元素
	virtual string GetCurrent() = 0;
};

//容器基类
class VecterBase
{
public:
	//添加元素
	virtual void Add(string elem) = 0;
	//获得当前元素
	virtual string Get(int index) = 0;
	//获得容器当前容量
	virtual int Count() = 0;
	//迭代器工厂
	virtual Iterator* CreateIterator() = 0;

};

//具体迭代器类
class ConcreteIterator : public Iterator
{
private:
	int m_currentIndex;
	VecterBase* m_vec;
public:
	ConcreteIterator(VecterBase* vec)
		:m_vec(vec)
		,m_currentIndex(0)
	{
	
	}

	virtual void Next() override
	{
		m_currentIndex++;
	}

	virtual void Begin()
	{
		m_currentIndex = 0;
	}
	
	virtual bool IsEnd()
	{
		return m_currentIndex >= m_vec->Count();
	}

	virtual string GetCurrent()
	{
		return m_vec->Get(m_currentIndex);
	}
};

//具体容器类
class ConcreteVector : public VecterBase
{
private:
	vector<string> stringvec;
public:
	void Add(string elem)
	{
		stringvec.push_back(elem);
	}

	string Get(int index)
	{
		return stringvec[index];
	}

	int Count()
	{
		return stringvec.size();
	}

	Iterator* CreateIterator()
	{
		return new ConcreteIterator(this);
	}
};

int _tmain(int argc, TCHAR* argv[])
{
	VecterBase* vec = new ConcreteVector();
	vec->Add("张三");
	vec->Add("李四");
	vec->Add("王二麻子");

	Iterator* it = vec->CreateIterator();
	for (it->Begin(); !it->IsEnd(); it->Next())
	{
		cout << it->GetCurrent() << endl;
	}

	//是不是很像STL里面的迭代器呢?
	/*for (std::vector<string>::iterator it = vec.begin(); it != vec.end(); ++it)
	{
	cout << (*it) << endl;
	}*/

	system("pause");
	
	return 0;
}
返回顶部