Adapter programming pattern comes in handy, when we would like to use a certain API, but have an object with a different interface. When so, we can use the adapter to wrap the strange interface with convenient API of ours. Plus, we can adapt the output to our needs.
What are the scenarios where we can use adapter design pattern? One could imagine one of the following:
- adaptation of a legacy system to modern needs
- unification of several different access channels
- modifying the returned output
Here is an example of adapter pattern in java code:
public class WeatherStation { public double getTemperature { sensor.getFahrenheit(); } public int getSensorId { sensor.getId(); } } public class CelsiusWeatherStationAdapter { private WeatherStation weatherStation; public CelsiusWeatherStationAdapter (WeatherStation weatherStation) { this.weatherStation = weatherStation; } public String getTemperatureInformation { String currentTemperature = weatherStation.getTemperature(); if (currentTemperature != null) { return String.format("Current temperature for sensor %d is %f.2", weatherStation.getId(), fahrenheitToCelsius(currentTemperature)); } else { return "Could not measure temperature"; } } }
Do you see what we have done here with the adapter pattern? We are now returning a full written information, including the sensor id. We have also translated Fahrenheit to Celsius and made it null safe in case the measurement cannot be acquired.
We have definitely changed the interface, but the underlying object is left intact.