Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Composite Pattern

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:

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

=

"  "

       

print

(

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

=

"  "

       

print

(

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

   

print

(

"=== File System Structure ==="

)

    root.

display

(

)

   

   

print

(

"\n=== Size Statistics ==="

)

   

print

(

f

"Total root size: {root.get_size()} bytes"

)

   

print

(

f

"Pictures directory size: {pictures.get_size()} bytes"

)

   

print

(

f

"Music directory size: {music.get_size()} bytes"

)

   

   

print

(

"\n=== Path Information ==="

)

   

print

(

f

"File path: {photo1.get_path()}"

)

   

print

(

f

"Directory path: {pictures.get_path()}"

)

   

   

print

(

"\n=== Find Component ==="

)

    found

=

root.

find_component

(

"song1.mp3"

)

   

if

found:

       

print

(

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

  1. Unified interface: clients can use individual objects and composite objects consistently
  2. Open-Closed Principle: easy to add new types of components without modifying existing code
  3. Simplifies client code: clients do not need to determine whether they are handling an individual object or a composite
  4. Flexible hierarchical structure: complex tree structures can be built

Disadvantages

  1. Design complexity: over-generalized design may make the system complex
  2. Type safety issues: in some cases, runtime type checking may be needed
  3. 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

)

:

       

print

(

"Render button"

)

class

Panel

(

UIComponent

)

:

   

"""Panel - composite node"""

   

def

init

(

self

)

:

       

self

.

children

=

[

]

   

   

def

add

(

self

,

component

)

:

       

self

.

children

.

append

(

component

)

   

   

def

render

(

self

)

:

       

print

(

"Start rendering panel"

)

       

for

child

in

self

.

children

:

            child.

render

(

)

       

print

(

"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:

  1. Implement file copy functionality
  2. Add file-type filtered search
  3. Implement depth-limited directory display

Exercise 2: Menu system design

Design a restaurant menu system with the following requirements:

Exercise 3: Organization chart

Create a company organization structure system:


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: