c++如何实现组合模式 c++设计模式之Composite【实例】

组合模式通过Component抽象接口统一处理Leaf和Composite,使客户端无需区分节点类型即可一致操作树形结构;核心是用std::unique_ptr管理内存、基类提供默认异常抛出,并避免循环引用。

组合模式(Composite Pattern)在 C++ 中用于统一处理单个对象(Leaf)和复合对象(Composite),让客户端可以一致地操作整个树形结构。核心是定义一个公共接口,让叶子节点和容器节点都实现它,从而屏蔽结构差异。

一、明确角色与接口设计

组合模式有三个关键角色:

  • Component(抽象构件):声明所有子类共有的操作(如 addremoveoperation),提供默认空实现或纯虚函数;
  • Leaf(叶子):不包含子节点,只实现自身行为,对管理子节点的操作(如 add)可抛异常或忽略;
  • Composite(容器):持有 std::vector<:unique_ptr>> 等子节点集合,转发操作到子节点,并支持动态增删。

二、C++ 实现示例(文件系统模拟)

模拟“文件(File)”和“目录(Directory)”,二者都可调用 display(),目录还能添加子项:

// Component.h
class Component {
public:
    virtual ~Component() = default;
    virtual void display(int indent = 0) const = 0;
    virtual void add(std::unique_ptr) { 
        throw std::runtime_error("add not supported for this component"); 
    }
    virtual void remove(const std::string&) { 
        throw std::runtime_error("remove not supported for this component"); 
    }
};
// Leaf: File.h
class File : public Component {
    std::string name_;
public:
    explicit File(std::string n) : name_(std::move(n)) {}
    void display(int indent) const override {
        std::cout << std::string(indent, ' ') << "? " << name_ << '\n';
    }
};
// Composite: Directory.h
class Directory : public Component {
    std::string name_;
    std::vector> children_;
public:
    explicit Directory(std::string n) : name_(std::move(n)) {}
    
    void display(int indent) const override {
        std::cout << std::string(indent, ' ') << "? " << name_ << '\n';
        for (const auto& child : children_) {
            child->display(indent + 2);
        }
    }

    void add(std::unique_ptr child) override {
        children_.push_back(std::move(child));
    }

    void remove(const std::string& targetName) override {
        children_.erase(
            std::remove_if(children_.begin(), children_.end(),
                [&targetName](const auto& c) -> bool {
                    // 简单匹配(实际可用 dynamic_cast 或 typeid 判断)
                    return c && c->getName() == targetName;
                }),
            children_.end()
        );
    }

    // 辅助:为演示加一个 getName(实际中可用 visitor 或其他方式解耦)
    virtual std::string getName() const { return name_; }
};

三、使用组合模式构建树并遍历

客户端代码无需区分叶子或容器,统一调用 display()

int main() {
    auto root = std::make_unique("root");
    
    root->add(std::make_unique("readme.md"));
    
    auto src = std::make_unique("src");
    src->add(std::make_unique("main.cpp"));
    src->add(std::make_unique("utils.h"));
    
    auto test = std::make_unique("test");
    test->add(std::make_unique("test_main.cpp"));
    
    root->add(std::move(src));
    root->add(std::move(test));

    root->display(); // 递归输出整棵树
}

输出效果:

? root
? readme.md
? src
? main.cpp
? utils.h
? test
? test_main.cpp

四、关键细节与注意事项

  • 内存安全优先:用 std::unique_ptr 管理子节点,避免裸指针和资源泄漏;
  • 接口职责清晰:叶子类不实现无意义的 add/remove,但保留接口——由基类提供默认异常抛出,比返回错误码更符合 C++ 惯例;
  • 避免循环引用:Composite 不应强持有父节点指针(除非需要向上遍历),否则易导致析构问题;
  • 扩展性考虑:若需不同类型的访问逻辑(如统计大小、搜索、序列化),可配合 Visitor 模式,而非在 Component 中堆砌方法。

不复杂但容易忽略:组合模式的价值不在“能写出来”,而在于它把“是否为容器”的判断从客户端逻辑中彻底剥离——只要面向 Component 编程,树有多深、混合多杂,都不影响调用方式。