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.

Medium Python 3.10+ Aug 9, 2026 OOP & classes 15 views 0 copies

Python code

37 lines
Python 3.10+
class 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

stdout
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

  1. Use a factory method inside the facade to instantiate subsystem components lazily
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.