00:00

Adapter Design Pattern in Java

Last updated:

The adapter design pattern in Java lets two classes with incompatible interfaces work together by placing a small translator class between them. The adapter implements the interface your code expects and internally calls the existing class, converting method names, parameters, units and results along the way.

It matters because you rarely control every API you depend on. A bank gateway that wants amounts in paise and answers with numeric codes, or a supplier API that returns pages instead of a list, will not change for you. Without an adapter, that vendor's quirks spread into your business logic. Adapter is a structural design pattern: it is about how classes fit together, not how they are created.

1. What Is the Adapter Design Pattern?

The GoF intent is: "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."

Think of a travel plug adapter. Your charger and the wall socket both work; they just have different shapes. The adapter changes the shape without changing either side. In code, the "shape" is the method signature, the data format or the error model.

An adapter implements the interface the client wants (the target) and holds a reference to the class that does the real work (the adaptee). Each target method converts its inputs, calls the adaptee, and converts the result back. There are two forms:

  • Object adapter: wraps the adaptee through composition. This is the normal choice in Java.
  • Class adapter: extends the adaptee and implements the target. Java's single inheritance limits it, and it only works when the adaptee is not final.

The object-oriented payoff is the Dependency Inversion Principle: business code depends on an interface you own, and the adapter is the only place that depends on the outside world.

2. Key Components

ComponentResponsibilityIn the Basic Example
TargetThe interface the client expectsPaymentProcessor
AdapteeExisting class with a useful but incompatible interfaceLegacyBankGateway
AdapterImplements the target and translates calls to the adapteeLegacyBankAdapter
ClientWorks only with the target interfaceCheckoutService

The client calls the target method on the adapter. The adapter translates the request, calls the adaptee, and translates the response. Neither the client nor the adaptee knows the other exists.

3. When Is Adapter Useful?

  • Integrating third-party or legacy code: a bank SDK with its own units and status codes that must fit your payment interface.
  • Plugging into standard Java APIs: making a paginated vendor API usable with for-each and streams by exposing it as an Iterable.
  • Supporting several providers: two courier SDKs with different data formats behind one tracking interface.

4. UML Class Diagram

The diagram shows the object adapter from the Basic Example.

Adapter UML class diagram CheckoutService uses the PaymentProcessor interface. LegacyBankAdapter implements PaymentProcessor and holds a reference to LegacyBankGateway, whose debit method it calls. CheckoutService uses «interface» PaymentProcessor + pay(orderId, rupees): PaymentResult Target implements LegacyBankAdapter - gateway: LegacyBankGateway + pay(orderId, rupees): PaymentResult Adapter wraps 1 LegacyBankGateway + debit(paise, ref): int Adaptee
Object adapter: LegacyBankAdapter implements the target interface and delegates to the wrapped LegacyBankGateway.
  1. CheckoutService depends only on PaymentProcessor (dashed "uses" arrow).
  2. LegacyBankAdapter implements that interface (dashed line, hollow triangle).
  3. The adapter holds one LegacyBankGateway in a private field: a navigable association with multiplicity 1.
  4. There is no line between the client and the adaptee. That missing line is the whole point of the pattern.

5. Step-by-Step Execution Flow

  1. At startup, the application creates the LegacyBankGateway, wraps it in a LegacyBankAdapter, and passes the adapter to CheckoutService as a PaymentProcessor.
  2. The client calls pay("ORD-1", 2499.00).
  3. The adapter converts rupees to paise (249900) and calls gateway.debit(249900, "ORD-1").
  4. The gateway returns the code 0.
  5. The adapter maps 0 to PaymentResult(true, "approved") and returns it.
  6. The client reads the result without ever seeing paise or numeric codes.

6. Real-World Use Cases

  • E-commerce: supplier catalogue feeds, tax engines and shipping carriers, each wrapped behind your own interface.
  • Payments and banking: one adapter per payment gateway or core-banking system, all implementing the same payment port.
  • Notifications: SMS and email vendor SDKs behind a single NotificationSender interface.
  • The JDK: InputStreamReader adapts a byte stream (InputStream) to a character stream (Reader). Arrays.asList() presents an array as a List, and Executors.callable(Runnable) turns a Runnable into a Callable.
  • Spring Framework: Spring MVC's DispatcherServlet calls handlers through HandlerAdapter implementations, such as RequestMappingHandlerAdapter for @RequestMapping methods. MessageListenerAdapter lets a plain method receive JMS messages.

7. Problem Without the Pattern

Checkout code that talks to the bank gateway directly:

CheckoutWithoutAdapter.java
import java.math.BigDecimal;

public class CheckoutWithoutAdapter {

    // Third-party code we cannot change: amounts in paise, results as numeric codes
    static final class LegacyBankGateway {
        int debit(long amountInPaise, String reference) {
            return amountInPaise > 1_000_000 ? 51 : 0;     // 0 = approved, 51 = insufficient funds
        }
    }

    // Business code speaks the vendor's language directly
    static final class CheckoutService {
        private final LegacyBankGateway gateway = new LegacyBankGateway();

        String checkout(String orderId, BigDecimal rupees) {
            long paise = rupees.movePointRight(2).longValueExact();   // unit conversion in business code
            int code = gateway.debit(paise, orderId);
            if (code == 0) return orderId + " paid";
            if (code == 51) return orderId + " declined: insufficient funds";
            return orderId + " failed with code " + code;            // vendor codes leak everywhere
        }
    }

    public static void main(String[] args) {
        CheckoutService checkout = new CheckoutService();
        System.out.println(checkout.checkout("ORD-1", new BigDecimal("2499.00")));
        System.out.println(checkout.checkout("ORD-2", new BigDecimal("15000.00")));
    }
}
Console
ORD-1 paid
ORD-2 declined: insufficient funds

The output is correct, but the design is not:

  • Tight coupling: CheckoutService creates and calls the vendor class itself.
  • Leaking details: paise conversion and code 51 live in business logic, and every caller repeats them.
  • Hard to change: moving to a new bank means rewriting checkout, refunds and reports.
  • Hard to test: there is no seam for a fake gateway.

8. Solution Using the Pattern

Define the interface your application wants, PaymentProcessor, with rupees in and a clear PaymentResult out. Write one adapter that translates between that interface and the bank gateway, and inject it into the checkout service.

The vendor's units and codes now live in exactly one class. A new bank is a new adapter; checkout does not change. Tests can pass a simple fake PaymentProcessor. The output in the Basic Example is the same as above, which is the point: the behaviour stays, and only the dependency direction changes.

9. Adapter Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Legacy Bank Gateway Adapter

Problem: fix section 7 so that checkout depends on its own interface instead of the vendor's.

PaymentAdapterDemo.java
import java.math.BigDecimal;

public class PaymentAdapterDemo {

    // Target: the interface our application wants
    interface PaymentProcessor {
        PaymentResult pay(String orderId, BigDecimal rupees);
    }

    record PaymentResult(boolean approved, String message) { }

    // Adaptee: third-party code with an incompatible interface
    static final class LegacyBankGateway {
        int debit(long amountInPaise, String reference) {
            return amountInPaise > 1_000_000 ? 51 : 0;     // 0 = approved, 51 = insufficient funds
        }
    }

    // Adapter: implements the target, wraps the adaptee and translates both ways
    static final class LegacyBankAdapter implements PaymentProcessor {
        private final LegacyBankGateway gateway;

        LegacyBankAdapter(LegacyBankGateway gateway) {
            this.gateway = gateway;
        }

        @Override
        public PaymentResult pay(String orderId, BigDecimal rupees) {
            long paise = rupees.movePointRight(2).longValueExact();   // request: rupees -> paise
            int code = gateway.debit(paise, orderId);
            return switch (code) {                                      // response: code -> result
                case 0 -> new PaymentResult(true, "approved");
                case 51 -> new PaymentResult(false, "insufficient funds");
                default -> new PaymentResult(false, "bank error " + code);
            };
        }
    }

    // Client: knows only the target interface
    static final class CheckoutService {
        private final PaymentProcessor payments;

        CheckoutService(PaymentProcessor payments) { this.payments = payments; }

        String checkout(String orderId, BigDecimal rupees) {
            PaymentResult result = payments.pay(orderId, rupees);
            return orderId + (result.approved() ? " paid" : " declined: " + result.message());
        }
    }

    public static void main(String[] args) {
        CheckoutService checkout = new CheckoutService(new LegacyBankAdapter(new LegacyBankGateway()));
        System.out.println(checkout.checkout("ORD-1", new BigDecimal("2499.00")));
        System.out.println(checkout.checkout("ORD-2", new BigDecimal("15000.00")));
    }
}

Important classes and methods

  • PaymentProcessor is the target, designed around the application's needs.
  • LegacyBankAdapter.pay() converts the request (rupees to paise) and the response (code to PaymentResult).
  • longValueExact() throws if the amount has fractions of a paisa, instead of silently truncating.

Expected output

Console
ORD-1 paid
ORD-2 declined: insufficient funds

How it runs

  1. main wraps the gateway in the adapter and injects it.
  2. ORD-1 (249,900 paise) is approved with code 0.
  3. ORD-2 (1,500,000 paise) exceeds the demo limit, so the gateway returns 51 and the adapter reports "insufficient funds".

10. Best Practices and Common Mistakes

Best practices

  • Design the target interface around your domain, not around the vendor's API.
  • Keep adapters thin: translate data, units and errors, nothing more.
  • Translate vendor exceptions, so no third-party type crosses into the domain.
  • Thread safety: adapters are usually stateless and can be shared, but they inherit the adaptee's limits. If the adaptee is not thread-safe, the adapter must synchronise or create one adaptee per call.

Common mistakes

  • Business rules in the adapter, such as discounts or retries mixed with translation.
  • Leaky targets that return vendor types, which defeats the point.
  • Lossy mapping: silently mapping unknown codes to "success".
  • Overengineering: wrapping a library whose interface already fits and is unlikely to be replaced.

11. When to Use and When Not to Use

Use it at system boundaries: vendor SDKs, legacy modules, other teams' services, or anywhere you expect to replace a dependency later.

Avoid it when you own both sides and can simply change one interface, when the two interfaces already match, or when the "translation" needs so much logic that a proper service or anti-corruption layer is the better design.

12. Advantages and Disadvantages

Advantages

  • Reuses existing code without modifying it.
  • Isolates vendor details in one class (Single Responsibility).
  • Swappable providers through new adapters (Open/Closed).
  • Testable clients that depend on interfaces.

Disadvantages

  • Extra classes and one more level of indirection.
  • Mapping can lose information when the two models differ.
  • A small runtime cost for conversion on every call.

13. Comparison with Similar Patterns

AspectAdapterFacadeDecoratorProxyBridge
IntentMake an existing interface fit anotherSimplify a whole subsystemAdd behaviourControl accessSeparate abstraction from implementation
Interface exposedDifferent from the wrapped objectNew, simpler interfaceSame as the wrapped objectSame as the wrapped objectAbstraction's own interface
WrapsUsually one objectMany objectsOne objectOne objectOne implementor
DesignedAfter the factAfter the factUp front or laterUp front or laterUp front

If the interface must change shape, use an Adapter. If you want fewer calls into a complex subsystem, use a Facade. If the interface stays the same and you add features, use a Decorator; if you add access control, caching or laziness, use a Proxy. If you are designing two dimensions that should vary independently from the start, use a Bridge.

14. Summary

  • The adapter design pattern in Java converts one interface into another that clients expect.
  • Purpose: reuse existing or third-party code without letting its API leak into your design.
  • Components: Target, Adaptee, Adapter, Client.
  • The adapter implements the target, wraps the adaptee, and translates requests, results and errors.
  • Used for payment gateways, couriers, supplier feeds, JDK streams and Spring MVC's HandlerAdapter.
  • Benefits: loose coupling, swappable providers, testable clients.
  • Keep adapters thin, prefer composition, and respect the adaptee's thread safety.

15. Java Design Pattern Interview Questions and Answers

Q1. What is the difference between an object adapter and a class adapter in Java?

An object adapter holds the adaptee in a field and works with any subclass of it. A class adapter extends the adaptee and implements the target, so it can override adaptee methods, but it is tied to one concrete class and cannot be used if that class is final. Because Java allows only one superclass, object adapters are the usual choice.

// Class adapter (needs a non-final LegacyBankGateway): inherits debit(), implements the target
class LegacyBankClassAdapter extends LegacyBankGateway implements PaymentProcessor {
    public PaymentResult pay(String orderId, BigDecimal rupees) {
        int code = debit(rupees.movePointRight(2).longValueExact(), orderId);
        return new PaymentResult(code == 0, code == 0 ? "approved" : "code " + code);
    }
}
Q2. Product asks you to add a "retry three times" rule inside the bank adapter. Is that a good idea?

Usually not. Retries are a resilience policy, not a translation, and putting them in the adapter hides them and duplicates them across adapters. Keep the adapter thin and add retries around the target interface, for example with a decorator or a library such as Resilience4j, so every adapter gets the same policy.

Q3. The adaptee is blocking, but your target interface returns CompletableFuture. How do you adapt it?

Run the blocking call on a dedicated executor inside the adapter and return the future. Use a bounded or virtual-thread executor so blocking calls do not exhaust the common pool.

public CompletableFuture<PaymentResult> payAsync(String orderId, BigDecimal rupees) {
    return CompletableFuture.supplyAsync(() -> pay(orderId, rupees), bankExecutor);
}
Q4. How do you test adapters for several vendors consistently?

Write one contract test suite against the target interface and run it for every adapter, so all adapters must behave the same way. Use stubbed adaptees for unit tests, and an HTTP stub server such as WireMock or the vendor's sandbox for integration tests of the real client.

Q5. How does an adapter relate to an anti-corruption layer in Domain-Driven Design?

An anti-corruption layer is a boundary that stops another system's model from leaking into your domain. It is usually built from adapters, translators and sometimes facades. A single adapter fixes one interface mismatch; an anti-corruption layer applies the same idea to a whole external model.