StructuralPythonverifiedVerified

Composite Pattern in Python

Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.

How to Implement the Composite Pattern in Python

1Step 1: Define the component interface for uniform treatment

from __future__ import annotations
from abc import ABC, abstractmethod


class Component(ABC):
    @abstractmethod
    def operation(self) -> str: ...

    def is_composite(self) -> bool:
        return False

2Step 2: Implement Leaf and Composite node types

class Leaf(Component):
    def __init__(self, name: str) -> None:
        self._name = name

    def operation(self) -> str:
        return f"Leaf({self._name})"


class Composite(Component):
    def __init__(self) -> None:
        self._children: list[Component] = []

    def add(self, component: Component) -> None:
        self._children.append(component)

    def remove(self, component: Component) -> None:
        self._children.remove(component)

    def is_composite(self) -> bool:
        return True

    def operation(self) -> str:
        results = "+".join(c.operation() for c in self._children)
        return f"Branch({results})"

3Step 3: Build a tree and traverse it uniformly

tree = Composite()
branch = Composite()
branch.add(Leaf("1"))
branch.add(Leaf("2"))
tree.add(branch)
tree.add(Leaf("3"))

print(tree.operation())
# Branch(Branch(Leaf(1)+Leaf(2))+Leaf(3))

Composite Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Composite Pattern in the Real World

A company’s org chart is a composite structure. An individual employee (leaf) has a salary and a name. A department (composite) also has a name and a budget—calculated by summing the salaries of all its members, which may themselves be other departments. HR can call ‘get budget’ on the CEO’s node and the entire tree is summed recursively.