StructuralPythonverifiedVerified
Facade Pattern in Python
Provides a simplified, unified interface to a complex subsystem, hiding its internal complexity from clients.
How to Implement the Facade Pattern in Python
1Step 1: Define the complex subsystem classes
class SubsystemA:
def operation_a(self) -> str:
return "SubsystemA: ready"
def operation_a2(self) -> str:
return "SubsystemA: go!"
class SubsystemB:
def operation_b(self) -> str:
return "SubsystemB: ready"
def operation_b2(self) -> str:
return "SubsystemB: fire!"2Step 2: Create the Facade that orchestrates the subsystems
class Facade:
def __init__(
self,
a: SubsystemA | None = None,
b: SubsystemB | None = None,
) -> None:
self._a = a or SubsystemA()
self._b = b or SubsystemB()
def simple_operation(self) -> str:
return "\n".join([
"Facade initialises subsystems:",
self._a.operation_a(),
self._b.operation_b(),
"Facade triggers subsystems:",
self._a.operation_a2(),
self._b.operation_b2(),
])3Step 3: Use the simplified Facade interface
def client_code(facade: Facade) -> None:
print(facade.simple_operation())
client_code(Facade())"""Media Conversion Facade hiding codec detection, transcoding, and metadata."""
import logging
from dataclasses import dataclass
from pathlib import Path
logger = logging.getLogger(__name__)
# [step] Define subsystem classes (stubs simulating real libraries)
class CodecDetector:
CODEC_MAP = {"mp4": "h264", "mkv": "h265", "avi": "xvid"}
def detect(self, file_path: str) -> str:
ext = Path(file_path).suffix.lstrip(".")
return self.CODEC_MAP.get(ext, "unknown")
class VideoTranscoder:
def transcode(self, input_path: str, output_path: str, codec: str) -> None:
logger.info("[Transcoder] %s -> %s using %s", input_path, output_path, codec)
class ThumbnailExtractor:
def extract(self, input_path: str, timecode_sec: int) -> str:
thumb = str(Path(input_path).with_suffix("")) + "_thumb.jpg"
logger.info("[Thumbnailer] extracted frame at %ds -> %s", timecode_sec, thumb)
return thumb
class MetadataWriter:
def write(self, file_path: str, meta: dict[str, str]) -> None:
logger.info("[Metadata] wrote to %s: %s", file_path, meta)
# [step] Define the facade options and result types
@dataclass(frozen=True)
class ConversionOptions:
output_format: str # "mp4" | "webm" | "mov"
thumbnail_at: int | None = None
metadata: dict[str, str] | None = None
@dataclass(frozen=True)
class ConversionResult:
output_path: str
thumbnail_path: str | None
detected_codec: str
# [step] Implement the Facade with a single convert() entry point
class MediaConversionFacade:
def __init__(self) -> None:
self._detector = CodecDetector()
self._transcoder = VideoTranscoder()
self._thumbnailer = ThumbnailExtractor()
self._meta_writer = MetadataWriter()
def convert(self, input_path: str, opts: ConversionOptions) -> ConversionResult:
codec = self._detector.detect(input_path)
output_path = str(Path(input_path).with_suffix(f".{opts.output_format}"))
self._transcoder.transcode(input_path, output_path, codec)
thumbnail_path = (
self._thumbnailer.extract(input_path, opts.thumbnail_at)
if opts.thumbnail_at is not None
else None
)
if opts.metadata:
self._meta_writer.write(output_path, opts.metadata)
return ConversionResult(output_path, thumbnail_path, codec)
# Usage
facade = MediaConversionFacade()
result = facade.convert("lecture.mkv", ConversionOptions(
output_format="mp4",
thumbnail_at=5,
metadata={"title": "Lecture 1", "author": "Prof. Smith"},
))
print("Done:", result)Facade Pattern Architecture
hourglass_empty
Rendering diagram...
lightbulb
Facade Pattern in the Real World
“A hotel concierge is a facade for the city’s complex infrastructure. Instead of you directly calling a taxi company, booking a restaurant, and arranging a museum ticket separately, the concierge handles all of it through a single conversation. The underlying services still exist in their full complexity—you just don’t deal with them directly.”