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

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

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

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

*/

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

相关推荐
2601_967979125 小时前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
是2的10次方啊14 小时前
设计模式与生活⑭:一栋楼,共用一份热
设计模式
是2的10次方啊2 天前
设计模式与生活⑬:你坐几号线,谁来运营是另一回事
设计模式
Tt有了t3 天前
设计模式速查
java·python·设计模式
一条Go3 天前
四个进程,一把锁:Alioth 的告警评测为什么不需要消息队列
后端·设计模式·架构
一缕82年的清风3 天前
被中产唾弃的“十元快剪”,藏着最狠的极客工程学
人工智能·设计模式
是2的10次方啊3 天前
设计模式与生活⑫:周报又到手,别从空白开始
设计模式
拆房老料3 天前
DeepSeek Super-agent 架构解析:从单任务 Agent 到持续运行的任务系统
人工智能·设计模式·系统架构
工一木子4 天前
设计模式与生活⑩:地铁没变,你换了个状态
设计模式
是2的10次方啊4 天前
设计模式与生活⑪:地铁里被打扰,别总靠自己硬扛
设计模式