C 設計模式 組合模式

2021-08-28 13:37:38 字數 2011 閱讀 1705

#ifndef __composite_h__

#define __composite_h__

#include #include #include //【說明】

// 組合模式的關鍵是定義了乙個抽象構件類,它既可以代表葉子,又可以代表容器,而客戶端針對該抽象構件類進行程式設計,無須知道它到底表示的是葉子還是容器,可以對其進行統一處理。

// 同時容器物件與抽象構件類之間還建立乙個聚合關聯關係,在容器物件中既可以包含葉子,也可以包含容器,以此實現遞迴組合,形成乙個樹形結構。

//【定義】

// 組合模式(composite) :將物件組合成樹形結構以表示「部分-整體」的層次結構,組合使得使用者對單個物件和組合物件的使用具有一致性。

//【角色】

// component(抽象構件):它可以是介面或抽象類,為葉子構件和容器構件物件宣告介面。

// leaf(葉子構件):它在組合結構中表示葉子節點物件,葉子節點沒有子節點,它實現了抽象構件中定義的介面。

// composite(容器構件):它在組合結構中表示容器節點物件,容器節點包含子節點,其子節點可以是葉子節點,也可以是容器節點,它提供乙個集合用於儲存子節點。

//【意義】

//如果不使用組合模式,客戶端**將過多地依賴於容器物件複雜的內部實現結構,容器物件內部實現結構的變化將引起客戶**的頻繁變化,帶來了**維護複雜、可擴充套件性差等弊端。

//組合模式通常可用來表示樹形結構,這種結構隨處可見,如公司裡的部門結構,計算機裡的目錄結構等。

//【示例】

//目錄條目,抽象出容器和內容的一致介面

class entry

virtual ~entry()

public:

virtual std::string getname() = 0;

virtual int getsize() = 0;

virtual entry * add(entry * entry); //不定義為純虛函式,放在entry裡實現,則可以在file中不實現該方法

virtual void printlist(const std::string& prefix) = 0;

};//檔案

class file : public entry

~file()

public:

virtual std::string getname();

virtual int getsize();

virtual void printlist(const std::string& prefix);

private:

std::string m_name;

int m_size;

};//目錄,維護乙個目錄條目列表

class directoty : public entry

;void testcomposite();

#endif

#include "composite.h"

entry * entry::add(entry * entry)

std::string file::getname()

int file::getsize()

void file::printlist(const std::string& prefix)

directoty::directoty(const std::string& name) : m_name(name)

directoty::~directoty() }}

std::string directoty::getname()

int directoty::getsize()

return size;

}entry * directoty::add(entry * entry)

void directoty::printlist(const std::string& prefix)

}void testcomposite()

C 設計模式 組合模式

一.概述 組合模式,將物件組合成樹形結構以表示 部分 整體 的層次結構,組合模式使得使用者對單個物件和組合物件的使用具有一致性。結構 1.component 是組合中的物件宣告介面,在適當的情況下,實現所有類共有介面的預設行為。宣告乙個介面用於訪問和管理component子部件。2.leaf 在組合...

C 設計模式 組合模式

一 組合模式的定義 組合多個物件形成樹形結構以表示具有部分 整體關係的層次結構。二 說明 組合模式關注那些包含葉子構件和容器構件的結構以及它們的組織形式,在葉子結構中不包含成員物件,而容器構件中包含成員物件,這些物件通過遞迴組合可構成乙個樹形結構。由於容器物件和葉子物件在功能上存在區別,因此在使用這...

C 設計模式 組合模式

目錄 基本概念 與例項 個人感覺qt的物件樹就是運用了這種設計模式!當然,只是個人感覺,本人並沒有研究qt的原始碼 組合模式 composite 將物件組合成樹形結構以表示 部分 整體 的層次結構。組合模式使得使用者對單個物件和組合物件的使用具有一致性。何時使用 需求中提現部分和整體的層次結構,開發...