Composite Pattern
This lesson discusses the composite pattern that lets us treat individual elements and group of elements as one.
We'll cover the following...
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.
Class Diagram
The class diagram consists of the following entities
- Component
- Leaf
- Composite
- Client
Example
Assume, that we now want to represent all the aircraft in the combined air forces of the NATO alliance. An air force is primarily made up of several aircraft but it can also have sub-air forces. For instance, the US has the 1st Air Force, ...