Adapter and Facade: Connect and Simplify
An existing sensor returns Fahrenheit while a new display expects Celsius. If the sensor cannot be changed, insert a converter. Adapter lets incompatible interfaces work together.
Match methods and meaning
class LegacySensor:
def read_fahrenheit(self):
return 77
class CelsiusAdapter:
def __init__(self, sensor):
self.sensor = sensor
def read_celsius(self):
return (self.sensor.read_fahrenheit() - 32) * 5 / 9
print(CelsiusAdapter(LegacySensor()).read_celsius())
The output is 25.0. CelsiusAdapter provides the expected read_celsius() method and converts the old sensor’s result. Adaptation may involve units and meaning, not just renaming a method.
Facade offers a simpler entry point
Sending a report may require reading data, formatting, saving, and delivery. A facade groups these calls behind something like send_report(). The underlying capabilities still exist and may remain directly accessible.
| Pattern | Main question | Example |
|---|---|---|
| Adapter | How do we match the expected interface? | Connect a Fahrenheit sensor to a Celsius interface |
| Facade | How do we simplify a complex workflow? | Offer several report-processing steps through one call |
One object can partly serve both purposes. Distinguishing the reasons helps prevent an oversized responsibility.
Check your understanding
A replacement library changes function names and result formats. What role helps keep existing callers unchanged?
Show explanation
An adapter translates to the calls and results expected by existing code. Changes to error behavior or asynchronous execution must also be reconciled with that contract.