首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 設計模式:組合模式(Composite Pattern)完整指南

     編輯:關於C++

模式意圖

將對象組合成樹形結構以表示「部分-整體」層次,使客戶端對單個對象和組合對象的使用具有一致性。

核心角色

  • Component:抽象構件,聲明公共接口(Operation, Add, Remove, GetChild),可提供默認實現。
  • Leaf:葉節點,無子節點,實現 Operation,Add/Remove 拋異常或空實現。
  • Composite:樹枝節點,維護子構件列表,實現 Add/Remove/GetChild,Operation 遞歸調用子節點。

關鍵設計決策:透明性 vs 安全性

  • 透明方式:Component 聲明所有管理方法(Add/Remove)。Leaf 也擁有這些方法(空實現/拋異常)。客戶端完全統一調用,但 Leaf 調用管理方法不安全。
  • 安全方式:僅 Composite 聲明管理方法。客戶端需區分 Leaf/Composite,失去透明性但類型安全。
  • GoF 建議:優先透明性,Leaf 中拋異常處理非法調用。

完整代碼示例(公司組織架構)

class Component {
    string name;
public:
    Component(string n):name(n){}
    virtual ~Component(){}
    virtual void Operation()=0;
    virtual void Add(Component*)=0;
    virtual void Remove(Component*)=0;
    virtual Component* GetChild(int)=0;
    string GetName() { return name; }
    virtual void Print()=0;
};

class Leaf : public Component {
public:
    Leaf(string n):Component(n){}
    void Operation() { cout<<"Leaf: "< children;
public:
    Composite(string n):Component(n){}
    ~Composite() { for(auto c:children) delete c; }
    void Operation() {
        cout<<"Composite: "<Operation();
    }
    void Add(Component* c) { children.push_back(c); }
    void Remove(Component* c) {
        auto it=find(children.begin(),children.end(),c);
        if(it!=children.end()) { delete *it; children.erase(it); }
    }
    Component* GetChild(int i) { return (i>=0&&iGetName()<

關鍵實現細節

  1. 內存管理:Composite 析構函數遞歸刪除子節點,客戶端無需手動管理。
  2. 列表存儲:用 vector 存儲子節點,支援動態增刪。
  3. 最大化接口:Component 盡可能多定義公共操作,Leaf/Composite 選擇性重寫。

應用場景

  • 文件系統(文件/目錄)
  • GUI 控件樹(容器/按鈕)
  • 組織架構、菜單系統、AST 語法樹

總結

組合模式以遞歸結構優雅解決「部分-整體」問題。關鍵在於 Component 接口設計(透明/安全權衡)與 Composite 的遞歸委派。掌握後,樹形結構操作變得極其簡潔統一。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved