Structural Design Pattern

Adapter Design Pattern in Java

Make incompatible interfaces work together without changing the existing classes.

In this lesson: The Adapter pattern converts the interface of an existing class into the interface expected by a client. It is helpful when integrating legacy code, third-party libraries, or services with a different API.

Overview

The client depends on the target interface. The adapter wraps the adaptee and translates each client operation into the adaptee's existing method calls.

Implementation

interface PaymentProcessor {
    void pay(double amount);
}

final class LegacyGateway {
    void makePaymentInCents(int cents) {
        System.out.println("Paid " + cents + " cents");
    }
}

final class GatewayAdapter implements PaymentProcessor {
    private final LegacyGateway gateway;

    GatewayAdapter(LegacyGateway gateway) {
        this.gateway = gateway;
    }

    public void pay(double amount) {
        gateway.makePaymentInCents((int) (amount * 100));
    }
}

The client can now use the target interface while the adapter handles translation to the legacy implementation.

PaymentProcessor processor =
    new GatewayAdapter(new LegacyGateway());

processor.pay(49.99);

Example usage

Use Adapter when an existing class provides useful behavior but its interface does not match what the client needs. The adapter keeps integration changes localized and lets the client continue using a stable interface.

When should you use it?

Use Adapter when an existing class provides useful behavior but its interface does not match what the client needs. It is a good choice for integrating legacy code or third-party libraries without changing the client API.

Next step: Continue with the Design Patterns course and explore the next pattern category.