Composite: Introduction

Get a brief introduction to the Composite design pattern.

The Composite design pattern allows us to efficiently create tree-like structures. This ability can be useful in many situations. For example, if we need to write software that manages a computer’s file system, we’d want to be able to create folders and files. Moreover, every folder can contain zero or more other folders. This makes a file system a good example of a tree-like structure that the Composite design pattern is intended to create.

Summarized concept of the Composite pattern

The Composite pattern can be summarized as follows:

  • There’s a Leaf object, which can’t contain other objects.
  • There’s a Composite object, which can contain either Leaf objects or other Composite objects.
  • There’s a Component interface that both the Composite and the Leaf objects implement.
  • The children of a Composite object are of the Component type, which makes it possible to add either Leaf or Composite objects to it.
  • It’s relatively easy to navigate through the object hierarchy and manipulate it.

So, if we use the file system as an example, a folder would be a Composite object, while a file would be a Leaf object.

Get hands-on with 1400+ tech skills courses.