What is the Facade Pattern
The Facade Pattern is a structural design pattern that provides a simplified interface to a complex subsystem. It defines a higher-level interface that makes the subsystem easier to use without exposing the underlying complexity.
The pattern promotes loose coupling between the client and the complex subsystem.
Pattern Structure
The Facade Pattern typically involves:
- A Facade class that provides a unified interface to the subsystem.
- One or more Subsystem Classes that implement the detailed behavior.
- Clients that interact with the facade instead of the subsystem directly.
Facade Pattern UML Diagram
Implementation Example in Python
The following example shows a facade for a home theater system that hides the complexity of individual components.
# Subsystems
class Amplifier:
def on(self):
print("Amplifier is on.")
def set_volume(self, level):
print(f"Setting volume to {level}.")
class DVDPlayer:
def on(self):
print("DVD Player is on.")
def play(self, movie):
print(f"Playing movie '{movie}'.")
class Projector:
def on(self):
print("Projector is on.")
def wide_screen_mode(self):
print("Projector in widescreen mode.")
class TheaterLights:
def dim(self, level):
print(f"Dimming lights to {level}%.")
# Facade
class HomeTheaterFacade:
def __init__(self, amp: Amplifier, dvd: DVDPlayer, projector: Projector, lights: TheaterLights):
self.amp = amp
self.dvd = dvd
self.projector = projector
self.lights = lights
def watch_movie(self, movie):
print("Get ready to watch a movie...")
self.lights.dim(30)
self.amp.on()
self.amp.set_volume(5)
self.projector.on()
self.projector.wide_screen_mode()
self.dvd.on()
self.dvd.play(movie)
# Example usage
amp = Amplifier()
dvd = DVDPlayer()
projector = Projector()
lights = TheaterLights()
home_theater = HomeTheaterFacade(amp, dvd, projector, lights)
home_theater.watch_movie("Inception")
When to Use
Use the Facade Pattern when:
- You want to provide a simple interface to a complex subsystem.
- There are many dependencies between clients and the implementation classes of an abstraction.
- You want to layer your subsystems to decouple higher-level components from lower-level implementation details.
Summary
The Facade Pattern abstracts away the complexity of a subsystem by exposing a simplified interface. It does not encapsulate subsystem classes but rather delegates to them, allowing the client to avoid direct interaction with intricate internal logic.