Card 07/ 08

ExerciseDifficulty: Advanced1 min

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.

  1. Name the target, the adaptee, the adapter you will write, and the client.
  2. Write the adapter as an object adapter.
  3. With the sensor reading 21.5 °C, say what the dashboard should show, then run it.
Show a solution
py
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()))
OutputRan with python:3.12-slim (Python 3.12.13)
Temperature: 70.7 F
The adapter holds the sensor and converts each reading on the way out.
The participants in the sensor exercise

The 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.