Composite Design Pattern

Get an overview of the composite design pattern.

Overview

Let’s take a top-down approach to understanding this pattern by starting with a definition. According to the Gang of Four book, “The composite design pattern composes objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly.”

Before going deeper into the definition, let’s discuss what is meant by individual objects and the composition of objects.

The composition of objects has child components, and leaf objects don’t have any child components.

For example, let’s say we have a computer system with directories and files. We can consider directories as a composition of objects because we can find files or directories or both of them inside directories. On the other hand, files are individual objects because they don’t store any child components. Composite design patterns allow clients to treat individuals and compositions uniformly.

Let’s explain why we might need to use the composite pattern. Say we need to find the size of the directory. The size can be computed by iterating over all directories and files under it and summing the individual file sizes.

In the composite design pattern, we would design a common interface called Component through which we would interact with files and directories that will return the total size. For files, it will return their sizes directly. For directories, it will calculate the size of the files and directories inside it.

Get hands-on with 1400+ tech skills courses.