Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Composite Design Pattern ใน C++

Composite pattern ใช้เมื่อต้องจัดการกลุ่มออบเจ็กต์คล้ายกับออบเจ็กต์เดียว Composite pattern รวมออบเจ็กต์ในโครงสร้างต้นไม้ แสดงลำดับชั้นส่วนและทั้งหมด เป็น structural pattern

Pattern นี้สร้างคลาสที่มีกลุ่มออบเจ็กต์ของตัวเอง คลาสนี้ให้วิธีแก้ไขกลุ่มออบเจ็กต์เดียวกัน

ตัวอย่าง: พนักงานในองค์กร (มีรูปภาพแสดงลำดับชั้น)

Composite และ Leaf ทั้งคู่ implement component ส่วนสำคัญคือ Composite class ที่ contain component objects (composition relationship)

ตัวอย่างโค้ด

#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, 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