组合模式 (Composite Pattern)
意图:将对象组合成树形结构以表示"部分-整体"的层次结构,使客户端对单个对象和组合对象的使用具有一致性。
基础组件
- Component (组件):声明组合中对象的接口
- Leaf (叶子节点):表示组合中的叶子对象
- Composite (复合组件):存储子组件,实现与子组件相关的操作
继承/实现关系
Component <|-- Leaf
Component <|-- Composite
Composite --> Component (组合关系)
应用场景
- 需要表示对象的"部分-整体"层次结构
- 希望客户端忽略组合对象与单个对象的不同
- 需要统一处理树形结构中的所有元素
C++ 实现(文件系统场景)
#include <iostream>
#include <memory>
#include <vector>
/*
* 组合模式
* 意图:将对象组合成树形结构以表示"部分-整体"的层次结构,使客户端对单个对象和组合对象的使用具有一致性。
* 基础组件:
* - Component (组件):声明组合中对象的接口
* - Leaf (叶子节点):表示组合中的叶子对象
* - Composite (复合组件):存储子组件,实现与子组件相关的操作
* 继承/实现关系:
* Leaf 和 Composite 都继承自 Component。
* Composite 包含对 Component 的引用,可以包含多个 Leaf 或其他 Composite 对象(组合关系)。
*/
// 组件接口(Leaf 和 Composite继承自它)
class FileSystemComponent {
public:
virtual void display(int depth = 0) const = 0;
virtual ~FileSystemComponent() = default;
};
// 叶子节点:文件
class File : public FileSystemComponent {
public:
File(const std::string& name) : name_(name) {}
void display(int depth = 0) const override {
std::string indent(depth * 2, ' ');
std::cout << indent << "- File: " << name_ << "\n";
}
private:
std::string name_;
};
// 复合组件:文件夹
class Folder : public FileSystemComponent {
public:
Folder(const std::string& name) : name_(name) {}
// 复合组件可以包含其他组件
void add(std::unique_ptr<FileSystemComponent> component) {
children_.push_back(std::move(component));
}
void display(int depth = 0) const override {
std::string indent(depth * 2, ' ');
std::cout << indent << "+ Folder: " << name_ << "\n";
for (const auto& child : children_) {
child->display(depth + 1);
}
}
private:
std::string name_;
std::vector<std::unique_ptr<FileSystemComponent>> children_;
};
void CompositePattern()
{
std::cout << std::string(13, '-') << " Composite Pattern " << std::string(13, '-') << "\n";
// 创建文件系统结构
auto root = std::make_unique<Folder>("Root");
auto documents = std::make_unique<Folder>("Documents");
documents->add(std::make_unique<File>("resume.docx"));
documents->add(std::make_unique<File>("project.pdf"));
auto images = std::make_unique<Folder>("Images");
images->add(std::make_unique<File>("photo1.jpg"));
images->add(std::make_unique<File>("photo2.png"));
auto music = std::make_unique<Folder>("Music");
music->add(std::make_unique<File>("song1.mp3"));
music->add(std::make_unique<File>("song2.flac"));
images->display();
// 构建树形结构
root->add(std::move(documents));
root->add(std::move(images));
root->add(std::move(music));
// 显示整个文件系统
root->display();
}
组件对应关系
FileSystemComponent→ 组件接口File→ 叶子节点Folder→ 复合组件
1267

被折叠的 条评论
为什么被折叠?



