《迭代器模式(极简c++)》

本文章属于专栏- 概述 - 《设计模式(极简c++版)》-CSDN博客


模式说明

  • 方案: 迭代器模式是一种行为型设计模式,它提供了一种方法来顺序访问一个容器对象中的各个元素,而不暴露该对象的内部表示。该模式通过引入迭代器对象来封装访问顺序,并让容器对象可以独立于其遍历算法进行变化。
  • 优点:
    • 将遍历算法和容器对象解耦,使得容器可以自由变化而不影响遍历操作。
    • 简化了容器的接口,使得容器只需关注自身的数据结构和操作。
  • 缺点:
    • 增加了迭代器对象的额外开销。
    • 对于某些简单的容器,引入迭代器模式可能会显得过于复杂。

本质思想:将对容器的遍历操作封装到迭代器对象中,使得遍历操作可以独立于容器实现。这样,容器可以改变其内部结构而不影响遍历操作。

实践建议:c++以及大部分语言中,都有自己封装好的第三方迭代器。如std::vector,业务代码一般不需要单独封装,而是把基类指针放到容器中,就可以实现去除实现细节的遍历。

代码示例

cpp 复制代码
#include <iostream>
#include <vector>

// 迭代器接口
class Iterator {
public:
    virtual int next() = 0;
    virtual bool hasNext() = 0;
};

// 容器接口
class Container {
public:
    virtual Iterator* getIterator() = 0;
    virtual void add(int element) = 0;
};

// 具体迭代器
class ConcreteIterator : public Iterator {
private:
    std::vector<int>& data;
    size_t index;

public:
    ConcreteIterator(std::vector<int>& container) : data(container), index(0) {}

    int next() override {
        return data[index++];
    }

    bool hasNext() override {
        return index < data.size();
    }
};

// 具体容器
class ConcreteContainer : public Container {
private:
    std::vector<int> data;

public:
    Iterator* getIterator() override {
        return new ConcreteIterator(data);
    }

    void add(int element) override {
        data.push_back(element);
    }
};

int main() {
    ConcreteContainer container;
    container.add(1);
    container.add(2);
    container.add(3);

    Iterator* it = container.getIterator();
    while (it->hasNext()) {
        std::cout << it->next() << " ";
    }
    std::cout << std::endl;

    delete it;
    return 0;
}

/*
Output:
1 2 3
*/
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
为思念酝酿的痛8 小时前
POSIX信号量
linux·运维·服务器·后端
小羊在睡觉8 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
cjhbachelor8 小时前
c++继承
c++
AI玫瑰助手8 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车8 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋8 小时前
C++14特性
开发语言·c++·c++14特性
swipe9 小时前
Neo4j + Graph RAG 医疗知识图谱工程实践:患者教育问答真正需要的是“关系可追溯”
后端·langchain·llm
源码宝10 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区10 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展