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

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

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

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

*/

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

相关推荐
香菇滑稽之谈8 分钟前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式
Seven972 小时前
【设计模式】使用解释器模式简化复杂的语法规则
java·后端·设计模式
Seven972 小时前
【设计模式】通过访问者模式实现分离算法与对象结构
java·后端·设计模式
wenbin_java2 小时前
设计模式之工厂模式:原理、实现与应用
java·开发语言·设计模式
Seven972 小时前
【设计模式】遍历集合的艺术:深入探索迭代器模式的无限可能
java·后端·设计模式
黄明基4 小时前
设计模式学习:1、在支付系统中的实战应用
设计模式
Seven9710 小时前
【设计模式】使用中介者模式实现松耦合设计
java·后端·设计模式
Seven9710 小时前
【设计模式】探索状态模式在现代软件开发中的应用
java·后端·设计模式
Seven9710 小时前
【设计模式】从事件驱动到即时更新:掌握观察者模式的核心技巧
java·后端·设计模式