Design Patterns with Python Examples - Part 3 - The Facade Pattern in Python
Overview: The Facade pattern provides a simplified interface to a complex subsystem, hiding underlying complexity.
Example Use Case: A home theater system that wraps multiple components (projector, speakers, lights) under a single interface.
class Projector:
def on(self): print("Projector on")
def off(self): print("Projector off")
class Lights:
def dim(self): print("Lights dimmed")
def on(self): print("Lights on")
class Speakers:
def play_sound(self): print("Speakers playing sound")
class HomeTheaterFacade:
def __init__(self):
self.projector = Projector()
self.lights = Lights()
self.speakers = Speakers()
def watch_movie(self):
print("Getting ready to watch a movie...")
self.lights.dim()
self.projector.on()
self.speakers.play_sound()
def end_movie(self):
print("Shutting down movie system...")
self.projector.off()
self.lights.on()
home_theater = HomeTheaterFacade()
home_theater.watch_movie()
home_theater.end_movie()
Why it’s useful: Reduces coupling between clients and complex systems, making code easier to maintain.