C++二十三种设计模式之迭代器模式

C++二十三种设计模式之迭代器模式

一、组成

抽象聚合类 :存储集合元素,声明管理集合元素接口。
具体聚合类 :实现管理集合元素接口。
抽象迭代器类 :声明访问和遍历聚合类元素的接口。
具体迭代器类:实现访问和遍历聚合类元素的接口。

二、特点

1、有两种定义模板的方式,template和template。建议使用template,与类定义区分明显。

2、具体聚合类使用抽象聚合类的智能指针成员变量时,需要通过this指针来调用,否则可能会出现找不到该变量的编译报错。

三、目的

不暴露集合底层实现细节的情况下访问和遍历集合中所有元素。

四、缺点

1、性能消耗问题,使用迭代器需要额外的间接层来访问元素,比直接访问元素慢。

2、类膨胀,为了支持多种遍历方式,需要定义多种具体迭代器类。

五、示例代码

javascript 复制代码
#include<iostream>
#include <vector>
#include <list>
#include <string>
#include <mutex>
#include <map>
#include<stack>

using namespace std;

template<typename T>
class Node;//节点类

template<typename T>
class AbstractLinkedList;//抽象聚合类

template<typename T>
class LinkedList;//具体聚合类

template<typename T>
class AbstractIterator;//抽象迭代器类

template<typename T>
class Iterator;//具体迭代器类

template<typename T>
class Node {
public:
	Node(T data) : m_data(data), next(nullptr) {}
	~Node() {
		cout << "~Node" << endl;
	}
	T m_data;
	shared_ptr<Node<T>> next;
};

template<typename T>
class AbstractIterator {
protected:
	AbstractIterator() {}
	virtual void Next() = 0;
	virtual bool hasNext() const = 0;
public:
	shared_ptr<Node<T>> m_current;
};

template<typename T>
class Iterator :public AbstractIterator<T> {//具体迭代器类
public:
	Iterator() {}
	Iterator(shared_ptr<Node<T>> cur) {
		this->m_current = cur;
	}
	void Next() {
		this->m_current = (this->m_current)->next;
	};
	bool hasNext() const {
		return ((this->m_current) != nullptr);
	};
};

template<typename T>
class AbstractLinkedList {
protected:
	virtual Iterator<T> Begin() = 0;
	virtual void append(T value) = 0;
	shared_ptr<Node<T>> m_head;
};

template<typename T>
class LinkedList :public AbstractLinkedList<T> {
public:
	Iterator<T> Begin() {
		return Iterator<T>(this->m_head);
	}

	void append(T value) {
		auto newNode = make_shared<Node<T>>(value);
		if (!this->m_head) {
			this->m_head = newNode;
		}
		else {
			auto cur = this->m_head;
			while (cur->next) {
				cur = cur->next;
			}
			cur->next = newNode;
		}
	}
};

int main() {
	unique_ptr<LinkedList<int>> linkedList = make_unique<LinkedList<int>>();
	linkedList->append(1);
	linkedList->append(2);
	linkedList->append(3);
	for (Iterator<int> iter = linkedList->Begin(); iter.hasNext(); iter.Next()) {
		cout << "value:" << iter.m_current->m_data << endl;
	}
}
相关推荐
利刃大大4 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车5 小时前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle5 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです5 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
Want5956 小时前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客6 小时前
c++ 杂记
开发语言·c++
jimmy.hua6 小时前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°6 小时前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx7 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
烛阴7 小时前
【TS 设计模式完全指南】从零到一:掌握TypeScript建造者模式,让你的对象构建链式优雅
javascript·设计模式·typescript