Member-only story
Easy patterns in Python: The Composite Pattern — Hacking With Python
Sometimes you want to handle part of an object in the same way as the whole object. This whole-part relationship is elegantly represented by the Composite pattern. As you will see, the implementation in Python is simple and elegant.
Introduction
The composite pattern allows you treat a group of objects like a single object. The objects are composed into some form of a tree-structure to make this possible.
This patterns solves two problems:
- Sometimes it is practical to treat part and whole objects the same way
- An object hierarchy should be represented as a tree structure
We do this by doing the following:
- Define a unified interface for both the part objects (Leaf) and the whole object (Composite)
- Composite delegate calls to that interface to their children, Leaf objects deal with them directly.
This all sounds rather cryptic, so let us have a look at the diagram:
This is basically a graphical representation of the last two points: Composites delegate and Leafs perform the actual operation.