C++怎么实现一个组合模式(Composite)_C++设计模式与组合模式实现

组合模式通过统一接口实现树形结构的“整体-部分”关系,C++中定义Component基类声明操作,Leaf实现个体行为,Composite管理子节点并递归调用,客户端无需区分对象类型,适用于菜单、文件系统等层级场景,推荐使用智能指针管理内存。

组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“整体-部分”层次结构。C++中实现组合模式的关键是让容器对象(Composite)和叶子对象(Leaf)拥有相同的接口,这样客户端可以统一处理单个对象和组合对象。

定义公共组件接口

首先要定义一个抽象基类 Component,声明所有组合节点共有的操作,比如添加、删除子节点或执行某种行为。

class Component {
public:
    virtual ~Component() = default;
    virtual void operation() const = 0;
    virtual void add(Component* child) {
        throw std::runtime_error("Not supported.");
    }
    virtual void remove(Component* child) {
        throw std::runtime_error("Not supported.");
    }
    virtual const std::vector& getChildren() const {
        throw std::runtime_error("Not supported.");
    }
    virtual bool isComposite() const { return false; }
};

实现叶子节点(Leaf)

叶子节点不包含子节点,只实现自己的行为。它不重写 add/remove 等方法,使用基类默认抛出异常的行为即可。

class Leaf : public Component {
public:
    void operation() const override {
        std::cout << "Leaf operation.\n";
    }
};

实现容器节点(Composite)

复合对象持有子组件列表,重写添加、删除和遍历方法,调用时会递归传递到所有子节点。

class Composite : public Component {
private:
    std::vector children_;

public: void operation() const override { std::cout << "Composite operation:\n"; for (const auto* child : children_) { child->operation(); } }

void add(Component* child) override {
    children_.push_back(child);
}

void remove(Component* child) override {
    children_.erase(
        std::remove(children_.begin(), children_.end(), child),
        children_.end()
    );
}

const std::vectorzuojiankuohaophpcnComponent*>& getChildren() const override {
    return children_;
}

bool isComposite() const override { return true; }

};

客户端使用示例

客户端无需区分叶子和复合对象,统一通过 Component 接口操作。

int main() {
    Component* leaf1 = new Leaf();
    Component* leaf2 = new Leaf();
    Component* composite = new Composite();
composite-youjiankuohaophpcnadd(leaf1);
composite-youjiankuohaophpcnadd(leaf2);

Component* sub_composite = new Composite();
sub_composite-youjiankuohaophpcnadd(new Leaf());
composite-youjiankuohaophpcnadd(sub_composite);

composite-youjiankuohaophpcnoperation();  // 递归执行所有子节点

// 清理资源(实际项目建议用智能指针)
delete leaf1;
delete leaf2;
delete sub_composite;
delete composite;

return 0;

}

基本上就这些。组合模式的核心在于统一接口和递归调用,适用于菜单、文件系统、UI控件树等具有层级结构的场景。注意内存管理,推荐用 std::unique_ptr 替代裸指针提升安全性。