Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

design
pattern
composite
uml
object oriented

What is the composite design pattern?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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:

  1. Component: The abstract parent class.
  2. Leaf: The child class, which is the smaller sibling and cannot contain anything (e.g., a file).
  3. Composite: The child class which can contain itself and the leaf (e.g., a folder).

UML diagram

svg viewer

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;
}

RELATED TAGS

design
pattern
composite
uml
object oriented
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring