Adapter Pattern Demo

Demo

package AdapterPatternDemo; public interface TemperatureReporter { double getTemperatureCelsius(); }
package AdapterPatternDemo; public class WeatherStationAdapter implements TemperatureReporter { private OutsideWeatherStation weatherStation; public WeatherStationAdapter(OutsideWeatherStation weatherStation) { this.weatherStation = weatherStation; } @Override public double getTemperatureCelsius() { double fahrenheit = weatherStation.getTemperatureFahrenheit(); return (fahrenheit - 32) * 5.0 / 9.0; } }
package AdapterPatternDemo; import java.util.List; public class WeatherReporter { private List<TemperatureReporter> stations; public WeatherReporter(List<TemperatureReporter> stations) { this.stations = stations; } public void report() { for (TemperatureReporter station : stations) { System.out.println("Current temperature in Celsius: " + station.getTemperatureCelsius()); } } }

Consider a scenario where a client application uses a TemperatureReporter interface to report temperature in Celsius. However, there is a third-party library that provides a OutsideWeatherStation class that reports temperature in Fahrenheit. We can't modify either the client or the third-party library, but we need to integrate them.

In this example, we have two OutsideWeatherStation instances, each of which provides the temperature in Fahrenheit. Our WeatherReporter expects a list of TemperatureReporter objects, so we wrap our OutsideWeatherStation objects in WeatherStationAdapter instances. The WeatherReporter can then call the getTemperatureCelsius method on these objects, oblivious to the fact that it's actually getting the data from OutsideWeatherStation objects.

 

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark