C++ 中的組合設計模式


如果我們希望將一組物件當作單個物件同等對待,就可以使用組合模式。組合模式按照樹結構對物件進行組合,以表示部分和整體層次結構。這種設計模式屬於結構模式,因為該模式建立了一組物件的樹結構。

這種模式建立了一個類,其中包含一組自身物件。該類提供了修改相同物件組的方法。

我們透過以下示例展示組合模式的使用,其中我們將展示組織的員工層次結構。

在這裡,我們可以看到組合和葉類都實現了元件。重要的部分是組合類,它還包含由組合關係表示的元件物件。

示例程式碼

#include <iostream>
#include <vector>
using namespace std;
class PageObject {
   public:
      virtual void addItem(PageObject a) { }
      virtual void removeItem() { }
      virtual void deleteItem(PageObject a) { }
};
class Page : public PageObject {
   public:
      void addItem(PageObject a) {
      cout << "Item added into the page" << endl;
   }
   void removeItem() {
      cout << "Item Removed from page" << endl;
   }
   void deleteItem(PageObject a) {
      cout << "Item Deleted from Page" << endl;
   }
};
class Copy : public PageObject {
   vector<PageObject> copyPages;
   public:
      void AddElement(PageObject a) {
         copyPages.push_back(a);
      }
      void addItem(PageObject a) {
         cout << "Item added to the copy" << endl;
      }
      void removeItem() {
         cout << "Item removed from the copy" << endl;
      }
      void deleteItem(PageObject a) {
         cout << "Item deleted from the copy";
      }
};
int main() {
   Page p1;
   Page p2;
   Copy myCopy;
   myCopy.AddElement(p1);
   myCopy.AddElement(p2);
   myCopy.addItem(p1);
   p1.addItem(p2);
   myCopy.removeItem();
   p2.removeItem();
}

輸出

Item added to the copy
Item added into the page
Item removed from the copy
Item Removed from page

更新時間:2019 年 7 月 30 日

1K+ 瀏覽量

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告