Composite Design Pattern in C++


Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects.

This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects.

We are demonstrating use of composite pattern via following example in which we will show employees hierarchy of an organization.

Here we can see the composite and leaf both classes are implementing the component. The important part is the composite class, this is also containing the component objects shown by the composition relationship.

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

Output

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

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements