← 返回博客列表

模式特点

将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式让客户端可以统一地处理单个对象和组合对象。

类图

类图

应用场景

示例代码(C++)

class UIComponent {
public:
    virtual void render(int depth = 0) = 0;
    virtual void add(UIComponent*) {}  // 默认空实现
    virtual ~UIComponent() = default;
};

// 叶节点
class Button : public UIComponent {
    std::string label;
public:
    Button(const std::string& l) : label(l) {}
    void render(int depth) override {
        std::cout << std::string(depth, ' ') << "[Button] " << label << std::endl;
    }
};

// 组合节点
class Panel : public UIComponent {
    std::vector<UIComponent*> m_children;
    std::string name;
public:
    Panel(const std::string& n) : name(n) {}
    void add(UIComponent* c) override { m_children.push_back(c); }
    void render(int depth) override {
        std::cout << std::string(depth, ' ') << "+ Panel: " << name << std::endl;
        for (auto* c : m_children) c->render(depth + 2);
    }
};

// 使用:统一操作叶节点和组合节点
Panel* mainPanel = new Panel("主面板");
mainPanel->add(new Button("确定"));
Panel* subPanel = new Panel("子面板");
subPanel->add(new Button("取消"));
mainPanel->add(subPanel);
mainPanel->render();  // 递归渲染整棵树