Composite Pattern
You will go over the composite pattern in detail with the aid of a coding example in this lesson.
We'll cover the following...
What is the composite pattern?
The composite pattern is used to structure objects in a tree-like hierarchy. Here, each node of the tree can be composed of either child node(s) or be a leaf (no children objects). This pattern allows the client to work with these components uniformly, that is, a single object can be treated exactly how a group of objects is treated.
This pattern allows the formation of deeply-nested structures. If a leaf object receives the request sent by the client, it will handle it. However, if the recipient is composed of children, the request is forwarded to the child components.
From the diagram, you can see that a composite pattern consists of the following:
-
Component: an abstract class that contains methods such as add, remove, get that are used in managing the children. The component can be a leaf object or composite.
-
Composite: it is the subclass that implements a component. It is composed of other components (children).
-
Leaf: it is the subclass that implements a component. It does not have children.
Let’s take a look at an example to see its implementation.
Example
Explanation
The illustration below provides a visualization of the hierarchy of the objects in the code above:
From the illustration above, you can see the hierarchy of ...