当前位置: 首页 > article >正文

C++ 设计模式-迭代者模式

迭代器模式(Iterator Pattern)提供一种顺序访问聚合对象元素的方法,同时不暴露其底层实现。以下是一个基于C++的书籍管理迭代器

#include <iostream>
#include <vector>
#include <string>

// 前向声明
class Book;

// 抽象迭代器接口
class Iterator {
public:
    virtual ~Iterator() = default;
    virtual void next() = 0;          // 移动到下一个元素
    virtual bool hasNext() const = 0; // 检查是否还有元素
    virtual Book current() const = 0; // 获取当前元素
};

// 具体元素类:书籍
class Book {
public:
    explicit Book(std::string name) : name_(std::move(name)) {}
    std::string getName() const { return name_; }
private:
    std::string name_;
};

// 抽象聚合接口
class BookCollection {
public:
    virtual ~BookCollection() = default;
    virtual Iterator* createIterator() const = 0; // 创建迭代器
    virtual void addBook(const Book& book) = 0;   // 添加元素(可选)
};

// 具体聚合类:书籍集合(基于数组/vector)
class Library : public BookCollection {
public:
    Iterator* createIterator() const override;

    void addBook(const Book& book) override {
        books_.push_back(book);
    }

    // 提供给迭代器的访问接口(保持封装性)
    size_t size() const { return books_.size(); }
    const Book& get(size_t index) const { return books_[index]; }

private:
    std::vector<Book> books_;
};

// 具体迭代器:图书馆迭代器
class LibraryIterator : public Iterator {
public:
    explicit LibraryIterator(const Library& library)
        : library_(library), index_(0) {}

    void next() override {
        if (hasNext()) ++index_;
    }

    bool hasNext() const override {
        return index_ < library_.size();
    }

    Book current() const override {
        return library_.get(index_);
    }

private:
    const Library& library_;
    size_t index_ = 0;
};

// 实现聚合类的工厂方法
Iterator* Library::createIterator() const {
    return new LibraryIterator(*this);
}

// 客户端使用示例
int main() {
    Library library;
    library.addBook(Book("Design Patterns"));
    library.addBook(Book("The C++ Programming Language"));
    library.addBook(Book("Effective Modern C++"));

    Iterator* it = library.createIterator();
    while (it->hasNext()) {
        Book book = it->current();
        std::cout << "Book: " << book.getName() << std::endl;
        it->next();
    }

    delete it; // 释放资源
    return 0;
}

关键点解析:

  1. 模式结构

    • Iterator:定义遍历接口(next, hasNext, current
    • ConcreteIteratorLibraryIterator):实现具体遍历逻辑
    • AggregateBookCollection):声明创建迭代器的接口
    • ConcreteAggregateLibrary):存储数据并返回关联的具体迭代器
  2. 实现细节

    • 集合类通过 size()get() 方法提供受控访问,避免暴露内部存储结构。
    • 迭代器持有集合的引用并通过索引跟踪遍历状态。
    • 通过虚函数实现多态,支持未来扩展新的集合类型。
  3. 优势

    • 解耦客户端与集合实现:客户端仅依赖迭代器接口,集合内部结构变化不影响调用方。
    • 支持多种遍历方式:可创建不同迭代器实现正序、逆序、过滤等遍历逻辑。
    • 简化聚合接口:集合只需提供基本数据访问方法,无需关注遍历细节。
  4. C++特性

    • 使用 const 正确性保证集合数据不被意外修改。
    • 通过虚析构函数确保资源正确释放。
    • 示例中使用裸指针 it 管理迭代器,实际建议使用 std::unique_ptr 等智能指针。

输出结果:

Book: Design Patterns
Book: The C++ Programming Language
Book: Effective Modern C++

http://www.kler.cn/a/559065.html

相关文章:

  • 代码随想录day19
  • 基于大模型的 SDL 需求阶段安全需求挖掘实战指南 —— 四步法实现从业务需求到风险矩阵的智能转换
  • Git版本控制系统---本地操作(万字详解!)
  • ROS2机器人开发--服务通信与参数通信
  • 【Git】远程操作
  • Spring Boot嵌入式服务器深度解析:从配置到调优的全方位指南
  • 本地部署AI模型 --- DeepSeek(一)
  • R包的作用及安装指南
  • FTP 实验(ENSP模拟器实现)
  • 视觉分析之边缘检测算法
  • androidnetflix手机版遥控器操作
  • http 协议和 https 协议的区别是什么?
  • DApp 开发入门指南
  • 【ubuntu24.04】pycharm安装pygraphviz
  • 一文熟练掌握Spring Framework
  • ElasticSearch查询指南:从青铜到王者的骚操作
  • 【linux核心命令】
  • 从零开始:VirtualBox安装Ubuntu 24.04.1 LTS
  • k8s学习记录:环境搭建(基于Kubeadmin)
  • 计算机毕业设计SpringBoot+Vue.jst0甘肃非物质文化网站(源码+LW文档+PPT+讲解)