Sitemap

Composite Design Pattern

2 min readJun 30, 2024

--

The Composite pattern is a structural design pattern that allows us to treat a group of objects as a single object. It allows us to create a hierarchy of objects where each object can be treated independently or as part of a group.

For example, let’s consider a file system. We have files, folders, and subfolders inside a root folder. We can treat each file or folder independently, or we can group them together as a subfolder.

Get Anant Nema’s stories in your inbox

Join Medium for free to get updates from this writer.

In JavaScript, we can create an abstract Component class that defines the common operations that can be performed on both files and folders. We can then create two classes, File and Folder, that extends the Component class.

class Component {
constructor(name) {
this.name = name;
}

add(component) {}
remove(component) {}
getChild(index) {}
operation() {}
}
class File extends Component {
constructor(name) {
super(name);
}
operation() {
console.log(this.name + " - File operation");
}
}
class Folder extends Component {
constructor(name) {
super(name);
this.children = [];
}
add(component) {
this.children.push(component);
}
remove(component) {
var componentIndex = this.children.indexOf(component);
this.children.splice(componentIndex, 1);
}
getChild(index) {
return this.children[index];
}
operation() {
console.log(this.name + " - Folder operation");
for (let child of this.children) {
child.operation();
}
}
}

Now, we can create a File and a Folder object and add them to another Folder object to create a hierarchy.

const rootFolder = new Folder("Root");
const file1 = new File("File 1");
const file2 = new File("File 2");
const subFolder = new Folder("Subfolder");
subFolder.add(file1);
subFolder.add(file2);
rootFolder.add(subFolder);
rootFolder.operation();

We can treat the subfolder and files as a single unit, i.e., the subfolder. When we call the

operation()

method on the rootFolder, it calls the

operation()

method on the subfolder, which, in turn, calls the

operation()

method on the files.

This is how Composite pattern allows us to create a hierarchy of objects and treat them as a single unit.

--

--