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+ 浏览量

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.