Linux C++ 056-设计模式之迭代器模式

Linux C++ 056-设计模式之迭代器模式

本节关键字:Linux、C++、设计模式、迭代器模式

相关库函数:

概念

迭代器模式(Iterator Pattern)是一种常用的设计模式。迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。迭代器模式属于行为型模式。

优缺点

优点

支持多种遍历方式:不同的迭代器可以定义不同的遍历方式。

简化聚合类:聚合类不需要关心遍历逻辑。

多遍历支持:可以同时对同一个聚合对象进行多次遍历。

扩展性:增加新的聚合类和迭代器类都很方便,无需修改现有代码。

缺点

系统复杂性:每增加一个聚合类,就需要增加一个对应的迭代器类,增加了类的数量。

使用场景

1、当需要遍历一个聚合对象,而又不希望暴露其内部结构时。

2、当需要访问聚合对象内容而不暴露其内部表示时,使用迭代器模式。

3、当需要为聚合对象提供多种遍历方式时,考虑使用迭代器模式。

4、为遍历不同的聚集结构提供如开始、下一个、是否结束、当前哪一项等统一的接口。

角色说明

迭代器模式包含以下几个主要角色:

迭代器接口(Iterator):定义了访问和遍历聚合对象中各个元素的方法,通常包括获取下一个元素、判断是否还有元素、获取当前位置等方法。

具体迭代器(Concrete Iterator):实现了迭代器接口,负责对聚合对象进行遍历和访问,同时记录遍历的当前位置。

聚合对象接口(Aggregate):定义了创建迭代器对象的接口,通常包括一个工厂方法用于创建迭代器对象。

具体聚合对象(Concrete Aggregate):实现了聚合对象接口,负责创建具体的迭代器对象,并提供需要遍历的数据。

示例代码

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

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

// 具体迭代器
class ConcreteIterator : public Iterator 
{
private:
    std::vector<int> data;
    size_t position;

public:
    ConcreteIterator(const std::vector<int>& data) : data(data), position(0) {}

    int next() override {
        if (hasNext()) {
            return data[position++];
        } else {
            throw std::out_of_range("No more elements");
        }
    }

    bool hasNext() override {
        return position < data.size();
    }
};

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

// 具体聚合
class ConcreteAggregate : public Aggregate 
{
private:
    std::vector<int> data;

public:
    ConcreteAggregate(const std::vector<int>& data) : data(data) {}

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

int main(int argc, char *argv[])
{
    std::vector<int> data = {1, 2, 3, 4, 5};

    // 使用迭代器遍历聚合对象
    Aggregate* aggregate = new ConcreteAggregate(data);
    Iterator* iterator = aggregate->createIterator();

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

    delete iterator;
    delete aggregate;

    return 0;
}
相关推荐
律宏阔5 小时前
WSL Docker 端口明明空闲,但就是绑不上端口
linux·windows
律宏阔5 小时前
WSL 突然断网,无法 ping 内网或外网
linux·windows
穷人小水滴5 小时前
用容器编译 VirtualBox 虚拟机软件 (ArchLinux, podman)
linux·容器·virtualbox
乱码三千5 小时前
如何优雅地直连无公网 IP 的远程 GPU 服务器
linux·人工智能·程序员
yunwei375 小时前
使用 eBPF 跟踪 Nginx 请求
linux·后端·性能优化
yunwei375 小时前
使用 eBPF 跟踪 MySQL 查询
linux·后端·性能优化
yunwei375 小时前
eBPF 示例教程:使用 XDP 捕获 TCP 信息
linux·后端·性能优化
GeW5 小时前
制造业高端化,为什么必须重估Linux和数据库?
linux
sarasuki5 小时前
为什么 Agent 工具需要一个「协议」而不是「框架」:MCP 成为标准的底层逻辑
设计模式·agent·mcp
GeW5 小时前
工业场景中的Linux与数据库选型:高端化转型的技术底座
linux