Composite Pattern — ELI5
Think about a file system on your computer. You have files and folders. A folder can contain files, other folders, or a mix. When you want to know the size of something, you don’t care whether it’s a file or a folder — you just ask “how big is this?”
If it’s a file, the answer is straightforward — 5 megabytes. If it’s a folder, it adds up all the files and folders inside it (which add up their contents too, and so on). Same question, same answer format, different internal work.
That’s the Composite Pattern. It lets you treat individual items and groups of items the same way.
Think of a company org chart. You can ask “what’s the total salary budget?” to one person (easy — just their salary) or to a department (it adds up everyone in it, including sub-departments). The question is the same regardless of whether you’re asking about a leaf or a tree.
Or think about a shopping cart. Some items are simple products. Others are bundles — a “starter kit” that contains three products. When calculating the total price, you treat bundles and individual products the same way: “what’s your price?” The bundle asks each of its items the same question and adds them up.
The pattern creates tree structures where branches and leaves share the same interface. Code that uses them doesn’t need to check “is this a single item or a group?” — it just works.
The one thing to remember: Composite Pattern means you can ask the same question to one thing or a group of things — and get a consistent answer either way.
See Also
- Python Adapter Pattern How Python's Adapter Pattern works like a travel power plug — making incompatible things work together.
- Python Bridge Pattern Why separating what something does from how it does it keeps your Python code from becoming a tangled mess.
- Python Builder Pattern Why building complex Python objects step by step beats cramming everything into one giant constructor.
- Python Facade Pattern How the Facade Pattern gives you one simple button instead of a confusing control panel in Python.
- Python Flyweight Pattern How the Flyweight Pattern saves memory by sharing common data instead of copying it thousands of times.