What is the composite design pattern?
The composite design pattern is used when two classes have a common parent, and one sibling can contain objects of its own and its sibling’s type. For example, a file and a folder are types of data (parent abstract class), but a folder can contain many files and folders.
The composite design pattern is used to write less code because it uses polymorphism to execute code of the right class. There are three main parts of this design pattern:
- Component: The abstract parent class.
- Leaf: The child class, which is the smaller sibling and cannot contain anything (e.g., a file).
- Composite: The child class which can contain itself and the leaf (e.g., a folder).
UML diagram
Implementation
#include <iostream>#include <vector>using namespace std;// Component:class Data{private:int size;public:// make the class abstract:virtual int getSize() = 0;};// Leaf:class File: public Data{private:int size;public:File(int i){size = i;}int getSize(){return size;}};// Composite:class Folder: public Data{private:int size;vector<Data*> d;public:int getSize(){int sum = 0;// Using polymorphism and recursion// to calculate the size of folder:for(int i = 0; i < d.size(); i++)sum = sum + (*(d.at(i))).getSize();return sum;}void add(Data* f){d.push_back(f);}};int main(){File f1(5), f2(10), f3(5), f4(10);Folder folder1;folder1.add(&f1);folder1.add(&f2);Folder folder2;folder2.add(&f3);folder1.add(&folder2);Folder folder3;folder3.add(&f4);// Print folder sizes:cout << "Folder 1 size: " << folder1.getSize()<< endl << "Folder 3 size: " << folder3.getSize()<< endl;return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved