Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Mẫu thiết kế Composite (Composite Design Pattern) trong C++

Mẫu Composite dùng khi cần đối xử với một nhóm đối tượng giống như một đối tượng đơn lẻ. Composite tổ chức đối tượng theo cấu trúc cây để thể hiện phần cũng như toàn thể phân cấp. Mẫu này thuộc nhóm Structural pattern vì tạo cấu trúc cây từ nhóm đối tượng.

Mẫu này tạo lớp chứa nhóm đối tượng của chính nó. Lớp này cung cấp cách sửa đổi nhóm đối tượng cùng loại.

Minh họa qua ví dụ thể hiện phân cấp nhân viên trong tổ chức.

Mẫu thiết kế Composite (Composite Design Pattern) trong C++

Ở đây thấy cả Composite và Leaf đều triển khai Component. Phần quan trọng là lớp Composite, nó cũng chứa đối tượng Component qua quan hệ composition.

Ví dụ Code

#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();
}

Kết quả

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