Composite
Last updated
Last updated
Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.
The Composite design pattern is a structural pattern that allows you to compose objects into tree structures to represent part-whole hierarchies.
It lets clients treat individual objects and compositions of objects uniformly.
In JavaScript, this pattern is quite useful for working with hierarchical data structures like trees.
Here's an example of how you might implement the Composite pattern in JavaScript:
In this example:
Component
is the base class for both leaf and composite objects.
It defines the common interface for all components in the tree.
Composite
represents a branch node in the tree.
It can have child components, which can be either leaf nodes or other composite nodes.
Leaf
represents a leaf node in the tree. It is the basic building block of the tree structure and does not have any child components.
We create a tree structure consisting of a composite (tree
) with two branches (branch1
and branch2
), each having a leaf (leaf1
and leaf2
).
We then print the tree structure.
This pattern allows you to treat individual objects and compositions of objects uniformly, which can be very useful when dealing with complex tree-like structures.