Card 07/ 08
Practice: Adapting a Celsius Sensor to a Fahrenheit Dashboard
The dashboard calls read_fahrenheit(); the new sensor only offers get_celsius().
A new sensor with an old dashboard is a natural Adapter, and this exercise asks you to name the participants and write the adapter. The dashboard calls read_fahrenheit() on whatever thermometer it is given. The new sensor, from another supplier, offers only get_celsius(), and neither class may change.
- Name the target, the adaptee, the adapter you will write, and the client.
- Write the adapter as an object adapter.
- With the sensor reading 21.5 °C, say what the dashboard should show, then run it.
Show a solution
class CelsiusSensor:
def get_celsius(self) -> float:
return 21.5
class Dashboard:
def show(self, thermometer) -> None:
print(f"Temperature: {thermometer.read_fahrenheit():.1f} F")
class FahrenheitAdapter:
def __init__(self, sensor: CelsiusSensor) -> None:
self._sensor = sensor
def read_fahrenheit(self) -> float:
return self._sensor.get_celsius() * 9 / 5 + 32
Dashboard().show(FahrenheitAdapter(CelsiusSensor()))Temperature: 70.7 FThe target is the interface the dashboard uses, read_fahrenheit(), which in Python is a shape rather than a declared class; the diagram names it Thermometer. The adaptee is CelsiusSensor, the adapter is FahrenheitAdapter, and the client is Dashboard. The conversion multiplies by 9/5 and adds 32, so 21.5 °C shows as 70.7 F.
← → move through sections and cards