How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
Python code
37 linesclass CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDrive:
def read(self, lba, size):
return f"data from sector {lba} ({size} bytes)"
class ComputerFacade:
def __init__(self):
self.cpu = CPU()
self.memory = Memory()
self.hard_drive = HardDrive()
def start(self):
self.cpu.freeze()
self.memory.load(0, self.hard_drive.read(0, 1024))
self.cpu.jump(0)
self.cpu.execute()
if __name__ == "__main__":
facade = ComputerFacade()
facade.start()
Output
CPU: freezing
Memory: loading 'data from sector 0 (1024 bytes)' at 0
CPU: jumping to 0
CPU: executing
How it works
The Facade pattern provides a simplified interface to a larger set of classes, decoupling client code from subsystem internals. Here, ComputerFacade composes CPU, Memory, and HardDrive and exposes a single start() method. When the client calls start(), the facade orchestrates the steps: freeze, load, jump, and execute, hiding that coordination. This makes the subsystem easier to use and test, and reduces dependencies on individual components.
Common mistakes
- Adding business logic inside the facade instead of delegating to subsystem classes
- Exposing subsystem objects through the facade instead of keeping them private
- Making the facade a god object that grows too large and complex
Variations
- Use a factory method inside the facade to instantiate subsystem components lazily
- Make the facade a singleton if only one instance is needed per application
Real-world use cases
- Wrapping a media player's audio/video codec and output device classes behind a single play() method.
- Simplifying a database connection pool and query executor into a repository facade with basic CRUD methods.
- Hiding the details of an order processing pipeline (validation, payment, shipping) behind a single place_order() call.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.