This pattern allows you to compose objects into tree structures, and treat individual objects and compositions of objects uniformly. This can be useful when you want to represent part-whole hierarchies, and treat both parts and whole objects uniformly.
Here is an example of the composite pattern in JavaScript:
}
}
}
}
}
}
}
}
}
composite.
composite.
composite.
// Output:
// Composite operation for Composite.
// Leaf operation for Leaf 1.
// Leaf operation for Leaf 2.
In this example, the Component class is an abstract class that defines the structure for a component in the composite, and the Leaf and Composite classes are concrete implementations of the Component class that represent leaves and composites in the composite structure.
The Leaf class has an operation() method that performs an operation specific to leaf objects, and the Composite class has an operation() method that performs an operation specific to composite objects, as well as calling the operation() method on each of its children.
To use the composite pattern, we create instances of the Leaf and Composite classes and add them to the composite structure by calling the add() method on the composite object. Then, when we want to perform an operation on the composite, we call the operation() method on the root of the composite structure.This will recursively call the operation() method on all of the objects in the composite, treating both leaves and composites uniformly.