设计模式-迭代器模式-笔记

动机(Motivaton)

在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们呢希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种"透明遍历"也为"同一种算法在多种集合对象上进行操作"提供了可能。

使用面向对象技术将这种遍历机制抽象为"迭代器对象"为"应对变化中集合对象"提供一种优雅的方式。

模式定义:

提供一种方法顺序访问一个集合对象中的各个元素,而又不暴露(稳定)该对象内部表示。

cpp 复制代码
#include <iostream>

template<typename T>
class Iterator {
public:
    virtual void first() = 0;
    virtual void next() = 0;
    virtual bool isDone() = 0;
    virtual T& current() = 0;
};

template<typename T>
class MyCollection {
public:
    Iterator<T>* GetIterator() {
        //...
    }
};

template<typename T>
class CollentionIterator : public Iterator<T> {
    MyCollection<T> mc;
public:
    CollentionIterator(const MyCollection<T>& c) : mc(c) {}

    void first() override {
        //...
    }

    void next() override {
        //...
    }

    void isDone() override {
        //...
    }

    T& current() override {
        //...
    }
};

int main() {
    MyCollection<int> mc;
    Iterator<int>* iter = mc.GetIterator();

    for (iter->first(); !iter->isDone(); iter->next()) {
        std::cout << iter->current() << std::endl;
    }
}

要点总结:

迭代抽象:访问一个集合对象的内容而无需暴露他的内部表示;

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

迭代器的健壮性考虑:遍历的同时更改迭代器所在集合机构,会导致问题。

相关推荐
T700_67518 分钟前
iPhone 16 Pro 语音笔记全攻略:高效捕捉灵感,智能记录生活
笔记·生活·iphone
试试勇气25 分钟前
Linux学习笔记(十七)--线程概念
linux·笔记·学习
·醉挽清风·1 小时前
学习笔记—Linux—文件系统
linux·笔记·学习
console.log('npc')1 小时前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
AI视觉网奇1 小时前
动作迁移算法笔记 2026
人工智能·笔记
handler012 小时前
基础算法:分治
c语言·开发语言·c++·笔记·学习·算法·深度优先
不想看见4042 小时前
Implement Queue using Stacks栈和队列--力扣101算法题解笔记
笔记·算法·leetcode
宇宙realman_9992 小时前
Git 本地版本控制极简使用笔记(Qt 项目专用)
笔记·git
A923A2 小时前
【Vue3大事件 | 项目笔记】第六天
vue.js·笔记·前端框架·前端项目
ysa0510303 小时前
模拟【打牌游戏】
数据结构·c++·笔记·算法