【C++】组合模式
目录
- 一、模式核心概念与结构
- 二、C++ 实现示例:文件系统
- 三、组合模式的关键特性
- 四、应用场景
- 五、组合模式与其他设计模式的关系
- 六、C++ 标准库中的组合模式应用
- 七、优缺点分析
- 八、实战案例:图形编辑器
- 九、实现注意事项
- 如果这篇文章对你有所帮助,渴望获得你的一个点赞!
组合模式(Composite Pattern)是一种【结构型】设计模式,它允许你将对象组合成树形结构以表示 “部分 - 整体” 的层次关系。这种模式使得客户端可以统一处理单个对象和对象组合,无需区分它们的具体类型。
一、模式核心概念与结构
组合模式包含三个核心角色:
- 组件(Component):定义组合中所有对象的通用接口,声明管理子组件的方法。
- 叶节点(Leaf):表示组合中的叶节点对象,没有子节点,实现组件接口。
- 组合节点(Composite):表示组合中的分支节点,包含子组件,实现组件接口并管理子组件。
二、C++ 实现示例:文件系统
以下是一个经典的组合模式示例,演示如何用组合模式表示文件系统:
#include <iostream>
#include <string>
#include <vector>
#include <memory>// 组件:文件系统元素
class FileSystemElement {
public:virtual ~FileSystemElement() = default;virtual void print(int depth = 0) const = 0;virtual size_t getSize() const = 0;virtual void add(std::shared_ptr<FileSystemElement> element) {}virtual void remove(std::shared_ptr<FileSystemElement> element) {}
};// 叶节点:文件
class File : public FileSystemElement {
private:std::string name;size_t size;public:File(const std::string& n, size_t s) : name(n), size(s) {}void print(int depth) const override {std::cout << std::string(depth * 2, ' ') << "- " << name << " (file, " << size << " bytes)" << std::endl;}size_t getSize() const override {return size;}
};// 组合节点:目录
class Directory : public FileSystemElement {
private:std::string name;std::vector<std::shared_ptr<FileSystemElement>> children;public:Directory(const std::string& n) : name(n) {}void print(int depth) const override {std::cout << std::string(depth * 2