大话设计模式之迭代器模式

迭代器模式是一种行为设计模式,它允许客户端逐个访问集合中的元素,而不暴露集合的底层表示。这种模式提供了一种方法来访问聚合对象中的各个元素,而不需要暴露其内部结构。

迭代器模式由以下几个关键角色组成:

  1. 迭代器(Iterator): 定义访问和遍历元素的接口,通常包括 next()hasNext() 等方法。

  2. 具体迭代器(ConcreteIterator): 实现迭代器接口,负责对集合进行遍历和导航。

  3. 聚合(Aggregate): 定义创建迭代器对象的接口。

  4. 具体聚合(ConcreteAggregate): 实现聚合接口,返回一个特定的迭代器实例。

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

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

// 具体迭代器
class ConcreteIterator : public Iterator {
public:
    ConcreteIterator(const std::vector<int>& collection) : collection_(collection), index_(0) {}

    bool hasNext() const override {
        return index_ < collection_.size();
    }

    int next() override {
        return collection_[index_++];
    }

private:
    const std::vector<int>& collection_;
    size_t index_;
};

// 聚合接口
class Aggregate {
public:
    virtual Iterator* createIterator() const = 0;
};

// 具体聚合
class ConcreteAggregate : public Aggregate {
public:
    ConcreteAggregate(const std::vector<int>& collection) : collection_(collection) {}

    Iterator* createIterator() const override {
        return new ConcreteIterator(collection_);
    }

private:
    std::vector<int> collection_;
};

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    ConcreteAggregate aggregate(numbers);
    Iterator* iterator = aggregate.createIterator();

    while (iterator->hasNext()) {
        std::cout << iterator->next() << " ";
    }
    std::cout << std::endl;

    delete iterator;

    return 0;
}

/*
在这个示例中,Iterator 是迭代器接口,定义了遍历集合元素的方法。ConcreteIterator 是具体迭代器,
实现了迭代器接口以遍历 std::vector 集合。Aggregate 是聚合接口,定义了创建迭代器的方法。
ConcreteAggregate 是具体聚合,实现了聚合接口以返回 ConcreteIterator 实例。

在 main() 函数中,我们创建了一个包含整数的 std::vector 集合,并使用迭代器遍历输出了其中的元素。

*/

觉得有帮助的话,打赏一下呗。。

相关推荐
董员外7 小时前
RAG 系统进化论(八):Agentic RAG(智能体式 RAG),从回答问题到完成任务
人工智能·后端·设计模式
董员外11 小时前
RAG 系统进化论(七):Multimodal RAG(多模态 RAG),当知识存在于表格、图片和页面中
人工智能·后端·设计模式
大山同学11 小时前
第 2 篇(03-04 章):代理设计原则与工具使用设计模式
设计模式
啦啦啦啦啦zzzz2 天前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
莫得感情 o2 天前
设计模式 03 · 工厂方法模式
设计模式·工厂方法模式
cyforkk2 天前
高并发核心设计模式:Single-Flight 原理与实战
设计模式
饼干哥哥2 天前
字节Seedance2.5终于上线,这次在收割谁?
人工智能·设计模式·前端框架
董员外2 天前
RAG 系统进化论(六):GraphRAG(基于知识图谱的 RAG),从相似文本走向实体关系
人工智能·后端·设计模式
鬼鬼鬼2 天前
从 Prompt 到 Harness:企业级 Agent 工程的完整演进之路
设计模式·架构·ai编程
啦啦啦啦啦zzzz2 天前
设计模式:原型模式
c++·设计模式·原型模式