Python Composite Pattern
The Composite Pattern is a structural design pattern that lets you compose objects into tree structures to represent "part-whole" hierarchies. It allows clients to treat individual objects and compositions of objects uniformly, without worrying about whether they are dealing with a single object or an entire composite structure.
A Real-Life Analogy
Imagine the organizational structure of a file system:
- A single file: is the most basic unit
- folder in the window: can contain multiple files or other folders
- Whether you operate on a file or a folder, you can perform operations such as "open", "delete", and "rename"
This "part-whole" hierarchical relationship is a typical application scenario of the Composite Pattern.
Core Components of the Composite Pattern
1. Component Interface
This is the core of the Composite Pattern, defining the common interface for all objects (including leaf nodes and composite nodes).
Example
from
abc
import
ABC
,
abstractmethod
from
typing
import
List
class
FileSystemComponent
(
ABC
)
:
"""File system component abstract base class"""
def
init
(
self
,
name:
str
)
:
self
.
name
=
name
self
.
parent
=
None
@
abstractmethod
def
display
(
self
,
indent:
int
=
0
)
None
:
"""Display component information"""
pass
@
abstractmethod
def
get_size
(
self
)
int
:
"""Get component size"""
pass
def
get_path
(
self
)
str
:
"""Get full path"""
if
self
.
parent
:
return
f
"{self.parent.get_path()}/{self.name}"
return
self
.
name
2. Leaf Node
Represents leaf objects in a composition; leaf nodes have no children.
Example
class
File
(
FileSystemComponent
)
:
"""File class - leaf node"""
def
init
(
self
,
name:
str
,
size:
int
)
:
super
(
)
.
init
(
name
)
self
._size
=
size
def
display
(
self
,
indent:
int
=
0
)
None
:
"""Display file information"""
spaces
=
" "
- indent
(
f
"{spaces}📄 {self.name} ({self._size} bytes)"
)
def
get_size
(
self
)
int
:
"""Return file size"""
return
self
._size
3. Composite Node
Represents a composite object that can contain child components, defining methods to store child components.
Example
class
Directory
(
FileSystemComponent
)
:
"""Directory class - composite node"""
def
init
(
self
,
name:
str
)
:
super
(
)
.
init
(
name
)
self
._children: List
[
FileSystemComponent
]
=
[
]
def
add
(
self
,
component: FileSystemComponent
)
None
:
"""Add child component"""
component.
parent
=
self
self
._children.
append
(
component
)
def
remove
(
self
,
component: FileSystemComponent
)
None
:
"""Remove child component"""
self
._children.
remove
(
component
)
component.
parent
=
None
def
display
(
self
,
indent:
int
=
0
)
None
:
"""Display the directory and all its child components"""
spaces
=
" "
- indent
(
f
"{spaces}📁 {self.name}/"
)
Recursively display all child components
for
child
in
self
._children:
child.
display
(
indent +
1
)
def
get_size
(
self
)
int
:
"""Calculate the total size of the directory (including all child components)"""
total_size
=
0
for
child
in
self
._children:
total_size +
=
child.
get_size
(
)
return
total_size
def
find_component
(
self
,
name:
str
)
FileSystemComponent:
"""Find a component by the specified name"""
for
child
in
self
._children:
if
child.
name
==
name:
return
child
if
isinstance
(
child
,
Directory
)
:
found
=
child.
find_component
(
name
)
if
found:
return
found
return
None
Complete example: file system simulation
Let us demonstrate the practical application of the Composite pattern with a complete example:
Example
def
demonstrate_composite_pattern
(
)
:
"""Demonstrate the use of the Composite pattern"""
Create the root directory
root
=
Directory
(
"root"
)
Create subdirectories
documents
=
Directory
(
"documents"
)
pictures
=
Directory
(
"pictures"
)
music
=
Directory
(
"music"
)
Create a file
readme
=
File
(
"README.txt"
,
1024
)
notes
=
File
(
"notes.md"
,
2048
)
photo1
=
File
(
"vacation.jpg"
,
1536000
)
photo2
=
File
(
"family.png"
,
2048000
)
song1
=
File
(
"song1.mp3"
,
4096000
)
song2
=
File
(
"song2.mp3"
,
5120000
)
Build the directory structure
root.
add
(
readme
)
root.
add
(
documents
)
root.
add
(
pictures
)
root.
add
(
music
)
documents.
add
(
notes
)
pictures.
add
(
photo1
)
pictures.
add
(
photo2
)
music.
add
(
song1
)
music.
add
(
song2
)
Display the entire file system structure
(
"=== File System Structure ==="
)
root.
display
(
)
(
"\n=== Size Statistics ==="
)
(
f
"Total root size: {root.get_size()} bytes"
)
(
f
"Pictures directory size: {pictures.get_size()} bytes"
)
(
f
"Music directory size: {music.get_size()} bytes"
)
(
"\n=== Path Information ==="
)
(
f
"File path: {photo1.get_path()}"
)
(
f
"Directory path: {pictures.get_path()}"
)
(
"\n=== Find Component ==="
)
found
=
root.
find_component
(
"song1.mp3"
)
if
found:
(
f
"File found: {found.get_path()}"
)
Run the demo
if
name
==
"main"
:
demonstrate_composite_pattern
(
)
Run the above code and you will see the following output:

UML class diagram of the Composite pattern

Advantages and disadvantages of the Composite pattern
Advantages
- Unified interface: clients can use individual objects and composite objects consistently
- Open-Closed Principle: easy to add new types of components without modifying existing code
- Simplifies client code: clients do not need to determine whether they are handling an individual object or a composite
- Flexible hierarchical structure: complex tree structures can be built
Disadvantages
- Design complexity: over-generalized design may make the system complex
- Type safety issues: in some cases, runtime type checking may be needed
- Performance considerations: for large hierarchies, recursive operations may affect performance
Practical Application Scenarios
1. GUI component system
Example
class
UIComponent:
"""UI component base class"""
def
render
(
self
)
:
pass
def
add
(
self
,
component
)
:
pass
class
Button
(
UIComponent
)
:
"""Button - leaf node"""
def
render
(
self
)
:
(
"Render button"
)
class
Panel
(
UIComponent
)
:
"""Panel - composite node"""
def
init
(
self
)
:
self
.
children
=
[
]
def
add
(
self
,
component
)
:
self
.
children
.
append
(
component
)
def
render
(
self
)
:
(
"Start rendering panel"
)
for
child
in
self
.
children
:
child.
render
(
)
(
"Finish rendering panel"
)
2. Organization structure management
Example
class
Employee:
"""Employee base class"""
def
get_salary
(
self
)
:
pass
class
Developer
(
Employee
)
:
"""Developer - leaf node"""
def
init
(
self
,
salary
)
:
self
.
salary
=
salary
def
get_salary
(
self
)
:
return
self
.
salary
class
Department
(
Employee
)
:
"""Department - composite node"""
def
init
(
self
)
:
self
.
employees
=
[
]
def
add
(
self
,
employee
)
:
self
.
employees
.
append
(
employee
)
def
get_salary
(
self
)
:
return
sum
(
emp.
get_salary
(
)
for
emp
in
self
.
employees
)
Practical Exercise
Exercise 1: Extend the file system
Add the following features to the file system:
- Implement file copy functionality
- Add file-type filtered search
- Implement depth-limited directory display
Exercise 2: Menu system design
Design a restaurant menu system with the following requirements:
- A menu can contain dishes or submenus
- Able to calculate the total price
- Support filtering dishes by category
Exercise 3: Organization chart
Create a company organization structure system:
- An employee can be an individual or a department
- A department can contain other employees or sub-departments
- Able to calculate the total headcount and total salary of a department
Summary
The Composite pattern handles individual objects and object compositions through a unified interface, making client code more concise and flexible. This pattern is especially suitable for hierarchical scenarios such as file systems, GUI components, and organizational structures.
Key Points:
- The component interface defines common operations for all objects
- Leaf nodes implement basic functionality
- Composite nodes manage child components and provide aggregate operations
- Clients do not need to distinguish between individual objects and object compositions