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

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

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

  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 集合,并使用迭代器遍历输出了其中的元素。

*/

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

相关推荐
Query*2 小时前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式
庸了个白4 小时前
一种面向 AIoT 定制化场景的服务架构设计方案
mqtt·设计模式·系统架构·aiot·物联网平台·动态配置·解耦设计
Meteors.8 小时前
23种设计模式——访问者模式 (Visitor Pattern)
设计模式·访问者模式
Vallelonga9 小时前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
en-route9 小时前
设计模式的底层原理——解耦
设计模式
杯莫停丶9 小时前
设计模式之:工厂方法模式
设计模式·工厂方法模式
Deschen9 小时前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
粘豆煮包10 小时前
系统设计 System Design -4-2-系统设计问题-设计类似 TinyURL 的 URL 缩短服务 (改进版)
设计模式·架构
top_designer12 小时前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
非凡的世界13 小时前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php