TechnologyZer
technologyzer.com

Adapter Design Pattern

The Adapter Design Pattern is a structural design pattern used to enable communication between two incompatible interfaces. It allows objects with incompatible interfaces to work together by providing a bridge between them.

5 real world example of Adapter Design Pattern

Power Adapter: Power adapter allows devices with different power requirements or plug types to connect to a power source.

File Format Converter: An adapter can convert data between different file formats, such as converting XML to JSON or vice versa.

Language Translator: An adapter can be used to translate text or speech from one language to another, making it compatible with different language processing systems.

Display Adapter: Display adapters convert the output signal from a computer’s graphics card into a format compatible with a display device, such as HDMI to VGA.

Database Adapter: When switching between different database systems, an adapter can be used to translate database-specific queries and operations to a common interface.
// Existing interface
public interface FahrenheitSensor {
    double getTemperatureInFahrenheit();
}

// Concrete implementation of Existing interface
public class RealFahrenheitSensor implements FahrenheitSensor {
    @Override
    public double getTemperatureInFahrenheit() {
        // Simulated temperature reading in Fahrenheit
        return 98.6; // Normal body temperature
    }
}

// Adapter Interface
public interface TemperatureSensorAdapter {
    double getTemperatureInCelsius();
}

// Implementation of the Adapter interface
public class TemperatureSensorAdapterImpl implements TemperatureSensorAdapter {
    private FahrenheitSensor fahrenheitSensor;

    public TemperatureSensorAdapterImpl(FahrenheitSensor fahrenheitSensor) {
        this.fahrenheitSensor = fahrenheitSensor;
    }

    @Override
    public double getTemperatureInCelsius() {
        // Convert Fahrenheit to Celsius
        return (fahrenheitSensor.getTemperatureInFahrenheit() - 32) * 5 / 9;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Fahrenheit sensor
        FahrenheitSensor fahrenheitSensor = new RealFahrenheitSensor();

        // Create an adapter for Fahrenheit sensor
        TemperatureSensorAdapter adapter = new TemperatureSensorAdapterImpl(fahrenheitSensor);

        // Get temperature in Celsius using the adapter
        double temperatureInCelsius = adapter.getTemperatureInCelsius();

        System.out.println("Temperature in Celsius: " + temperatureInCelsius);
    }
}

Leave a Comment