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

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

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

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

*/

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

相关推荐
阿闽ooo3 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4963 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃3 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20103 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈3 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||3 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智4 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香4 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20104 天前
设计模式之备忘录模式
设计模式·备忘录模式
驴儿响叮当20104 天前
设计模式之迭代器模式
设计模式·迭代器模式