Composite Pattern: Definition, Example, and When to Use
Composite Pattern is a design pattern that lets you treat individual objects and groups of objects uniformly by organizing them into tree structures. It allows clients to work with single objects and compositions of objects through the same interface, simplifying code that deals with complex hierarchies.How It Works
The Composite Pattern works by creating a tree-like structure where each node can be either a single object (called a leaf) or a group of objects (called a composite). Both leaves and composites implement the same interface, so the client can treat them the same way without worrying about their differences.
Imagine a company where employees can be individual workers or managers who have teams. Both workers and managers can perform tasks, but managers also manage other employees. The Composite Pattern lets you call the same method on a single worker or a whole team, and it will work correctly.
Example
This example shows a simple file system where files and folders are treated the same. Both have a display method. Folders can contain files or other folders.
from abc import ABC, abstractmethod class FileSystemComponent(ABC): @abstractmethod def display(self, indent=0): pass class File(FileSystemComponent): def __init__(self, name): self.name = name def display(self, indent=0): print(' ' * indent + f'File: {self.name}') class Folder(FileSystemComponent): def __init__(self, name): self.name = name self.children = [] def add(self, component): self.children.append(component) def display(self, indent=0): print(' ' * indent + f'Folder: {self.name}') for child in self.children: child.display(indent + 1) # Usage root = Folder('root') file1 = File('file1.txt') file2 = File('file2.txt') subfolder = Folder('subfolder') file3 = File('file3.txt') root.add(file1) root.add(subfolder) subfolder.add(file2) subfolder.add(file3) root.display()
When to Use
Use the Composite Pattern when you need to work with tree structures where individual objects and groups of objects should be treated the same way. It is helpful when you want to simplify client code that deals with complex hierarchies.
Common real-world uses include graphical user interfaces where windows contain panels and buttons, file systems with folders and files, or organizational charts with employees and managers.
Key Points
- The Composite Pattern lets you treat single objects and groups uniformly.
- It uses a common interface for leaves and composites.
- It simplifies client code by hiding tree structure complexity.
- It is ideal for representing part-whole hierarchies.