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;
}
关键点解析:
-
模式结构:
- Iterator:定义遍历接口(
next
,hasNext
,current
) - ConcreteIterator(
LibraryIterator
):实现具体遍历逻辑 - Aggregate(
BookCollection
):声明创建迭代器的接口 - ConcreteAggregate(
Library
):存储数据并返回关联的具体迭代器
- Iterator:定义遍历接口(
-
实现细节:
- 集合类通过
size()
和get()
方法提供受控访问,避免暴露内部存储结构。 - 迭代器持有集合的引用并通过索引跟踪遍历状态。
- 通过虚函数实现多态,支持未来扩展新的集合类型。
- 集合类通过
-
优势:
- 解耦客户端与集合实现:客户端仅依赖迭代器接口,集合内部结构变化不影响调用方。
- 支持多种遍历方式:可创建不同迭代器实现正序、逆序、过滤等遍历逻辑。
- 简化聚合接口:集合只需提供基本数据访问方法,无需关注遍历细节。
-
C++特性:
- 使用
const
正确性保证集合数据不被意外修改。 - 通过虚析构函数确保资源正确释放。
- 示例中使用裸指针 it 管理迭代器,实际建议使用
std::unique_ptr
等智能指针。
- 使用
输出结果:
Book: Design Patterns
Book: The C++ Programming Language
Book: Effective Modern C++