Composite Pattern

This lesson discusses the composite pattern that lets us treat individual elements and group of elements as one.

What is it ?

Composite literally means made up of various elements or parts. The pattern allows you to treat the whole and the individual parts as one. The closest analogy you can imagine is a tree. The tree is a recursive data-structure where each part itself is a sub-tree except for the leaf nodes. The root is the top-level composite and its children are either composites themselves or just leaf nodes. The leaf itself can be thought of as a tree with just a single node.

Formally, the composite pattern is defined as composing objects into tree structures to represent part-whole hierarchies, thus letting clients uniformly treat individual objects and composition of objects.

The pattern allows the clients to ignore the differences between the whole and the part.

Get hands-on with 1200+ tech skills courses.