Middle+
What is the Composite pattern?
sobes.tech AI
Answer from AI
Composite — a structural pattern that allows objects to be combined into tree structures to represent hierarchies of part-whole relationships. It enables clients to work with individual objects and compositions uniformly.
Key ideas:
- Common interface: A common interface is defined for both leaf (individual) objects and composite (container) objects.
- Leaf: Represents a terminal object in the hierarchy. It has no children.
- Composite: Represents an object that contains child elements. It can contain both Leaves and other Composites.
- Recursive structure: Operations defined in the common interface can be implemented for both Leaves and Composites. For Composites, these operations are usually delegated recursively to their children.
Advantages:
- Simplifies client code, as it works with a single interface.
- Makes it easy to add new object types (Leaves or Composites) without breaking existing structures.
- Facilitates building complex hierarchical structures.
Disadvantages:
- Can complicate the code structure if objects differ significantly.
- Violates the single responsibility principle, as composite classes may be responsible for both their own behavior and managing child elements.
Example structure:
# Common interface for all components
class Component:
def operation(self):
pass
def add(self, component):
pass
def remove(self, component):
pass
def get_children(self):
pass
# Leaf - terminal object without children
class Leaf(Component):
def __init__(self, name):
self._name = name
def operation(self):
# Implementation of operation for leaf
print(f"Operation for Leaf: {self._name}")
# add/remove/get_children methods are empty for leaf
def add(self, component):
print("Cannot add to a leaf")
def remove(self, component):
print("Cannot remove from a leaf")
def get_children(self):
return []
# Composite - object containing child elements
class Composite(Component):
def __init__(self, name):
self._name = name
self._children = []
def operation(self):
# Implementation of operation for composite (delegating to children)
print(f"Operation for Composite: {self._name}")
for child in self._children:
child.operation()
def add(self, component):
self._children.append(component)
def remove(self, component):
self._children.remove(component)
def get_children(self):
return self._children
# Example usage
root = Composite("Root")
branch1 = Composite("Branch 1")
branch1.add(Leaf("Leaf 1.1"))
branch1.add(Leaf("Leaf 1.2"))
branch2 = Composite("Branch 2")
branch2.add(Leaf("Leaf 2.1"))
root.add(branch1)
root.add(branch2)
root.add(Leaf("Leaf 3"))
root.operation() # Performs operation for the entire hierarchy