Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 복합 디자인 패턴

<시간/>

복합 패턴은 단일 개체와 유사한 방식으로 개체 그룹을 처리해야 하는 경우에 사용됩니다. 복합 패턴은 전체 계층뿐만 아니라 부분을 나타내는 트리 구조의 관점에서 개체를 구성합니다. 이러한 유형의 디자인 패턴은 이 패턴이 개체 그룹의 트리 구조를 생성하므로 구조적 패턴에 속합니다.

이 패턴은 자체 개체 그룹을 포함하는 클래스를 만듭니다. 이 클래스는 동일한 개체 그룹을 수정하는 방법을 제공합니다.

우리는 조직의 직원 계층을 보여줄 다음 예를 통해 복합 패턴의 사용을 보여주고 있습니다.

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