The Composite Pattern is a structural design pattern that allows you to treat individual objects and compositions of objects uniformly. It represents a hierarchical structure of objects, making them work as a single object. To understand the Composite Pattern better, let’s look at an example:
class Component: def operation(self): pass class Leaf(Component): def operation(self): return "Leaf operation" class Composite(Component): def __init__(self): self.children = [] def add(self, component): self.children.append(component) def remove(self, component): self.children.remove(component) def operation(self): results = [] for child in self.children: results.append(child.operation()) return f"Composite operation: {', '.join(results)}"
In this example, we have three classes:
-
The
Component class is the base class that defines the common interface for both leaf and composite objects. It includes anoperation() method that will be implemented by the subclasses. -
The
Leaf class represents individual objects in the hierarchy. It implements theoperation() method specific to leaf objects. -
The
Composite class represents the composite object that can contain leaf objects as well as other composite objects. It maintains a list of child components and implements theoperation() method by recursively calling theoperation() method on each child component.
Here’s how you can use the Composite Pattern:
leaf1 = Leaf() leaf2 = Leaf() composite = Composite() composite.add(leaf1) composite.add(leaf2) print(composite.operation()) # Output: Composite operation: Leaf operation, Leaf operation
In this code, we create instances of the
The Composite Pattern allows you to treat individual objects and compositions of objects uniformly. It simplifies the client code by treating the composite and leaf objects in a consistent manner. It is useful when you want to represent part-whole hierarchies and perform operations on the entire hierarchy as if it were a single object.
Remember, the Composite Pattern is just one of many design patterns that can be used to solve specific problems. It provides a way to represent hierarchical structures and work with them uniformly.