Adapter Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Target | The interface the client expects | PaymentProcessor |
| Adaptee | Existing class with a useful but incompatible interface | LegacyBankGateway |
| Adapter | Implements the target and translates calls to the adaptee | LegacyBankAdapter |
| Client | Works only with the target interface | CheckoutService |
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-eachand streams by exposing it as anIterable. - 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.
LegacyBankAdapter implements the target interface and delegates to the wrapped LegacyBankGateway.CheckoutServicedepends only onPaymentProcessor(dashed "uses" arrow).LegacyBankAdapterimplements that interface (dashed line, hollow triangle).- The adapter holds one
LegacyBankGatewayin a private field: a navigable association with multiplicity 1. - 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
- At startup, the application creates the
LegacyBankGateway, wraps it in aLegacyBankAdapter, and passes the adapter toCheckoutServiceas aPaymentProcessor. - The client calls
pay("ORD-1", 2499.00). - The adapter converts rupees to paise (249900) and calls
gateway.debit(249900, "ORD-1"). - The gateway returns the code
0. - The adapter maps
0toPaymentResult(true, "approved")and returns it. - 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
NotificationSenderinterface. - The JDK:
InputStreamReaderadapts a byte stream (InputStream) to a character stream (Reader).Arrays.asList()presents an array as aList, andExecutors.callable(Runnable)turns aRunnableinto aCallable. - Spring Framework: Spring MVC's
DispatcherServletcalls handlers throughHandlerAdapterimplementations, such asRequestMappingHandlerAdapterfor@RequestMappingmethods.MessageListenerAdapterlets a plain method receive JMS messages.
7. Problem Without the Pattern
Checkout code that talks to the bank gateway directly:
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")));
}
}
ORD-1 paid
ORD-2 declined: insufficient funds
The output is correct, but the design is not:
- Tight coupling:
CheckoutServicecreates and calls the vendor class itself. - Leaking details: paise conversion and code
51live 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.
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
PaymentProcessoris the target, designed around the application's needs.LegacyBankAdapter.pay()converts the request (rupees to paise) and the response (code toPaymentResult).longValueExact()throws if the amount has fractions of a paisa, instead of silently truncating.
Expected output
ORD-1 paid
ORD-2 declined: insufficient funds
How it runs
mainwraps the gateway in the adapter and injects it.- ORD-1 (249,900 paise) is approved with code 0.
- ORD-2 (1,500,000 paise) exceeds the demo limit, so the gateway returns 51 and the adapter reports "insufficient funds".
Practical Example: Paginated Supplier API as an Iterable
Problem: a supplier returns its catalogue one page at a time. The team wants to use ordinary for-each loops and streams, and to fetch only the pages actually needed.
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class PagedCatalogAdapterDemo {
// Adaptee: a supplier's paginated catalogue API
record CatalogPage(List<String> skus, boolean hasNext) { }
static final class SupplierCatalogClient {
private static final List<List<String>> PAGES = List.of(
List.of("SKU-101", "SKU-102", "SKU-103"),
List.of("SKU-201", "SKU-202", "SKU-203"),
List.of("SKU-301"));
CatalogPage fetchPage(int pageNumber) {
System.out.println(" [supplier] fetching page " + pageNumber); // a remote call in real life
return new CatalogPage(PAGES.get(pageNumber), pageNumber < PAGES.size() - 1);
}
}
// Adapter: presents the paginated API as a standard Iterable
static final class SupplierCatalogIterable implements Iterable<String> {
private final SupplierCatalogClient client;
SupplierCatalogIterable(SupplierCatalogClient client) { this.client = client; }
@Override
public Iterator<String> iterator() {
return new Iterator<>() {
private int nextPage = 0;
private CatalogPage current = null;
private int index = 0;
@Override
public boolean hasNext() {
while (current == null || index == current.skus().size()) {
if (current != null && !current.hasNext()) {
return false;
}
current = client.fetchPage(nextPage++); // fetch lazily, one page at a time
index = 0;
}
return true;
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return current.skus().get(index++);
}
};
}
}
public static void main(String[] args) {
Iterable<String> catalogue = new SupplierCatalogIterable(new SupplierCatalogClient());
System.out.println("for-each over the whole catalogue:");
for (String sku : catalogue) {
System.out.println(" " + sku);
}
System.out.println("Stream, stopping after 4 items:");
String firstFour = StreamSupport.stream(catalogue.spliterator(), false)
.limit(4)
.collect(Collectors.joining(", "));
System.out.println(" " + firstFour);
}
}
Important classes and methods
- The target here is a JDK interface,
Iterable<String>, so every Java tool that accepts anIterablenow works with the supplier. hasNext()fetches the next page only when the current one is used up.next()follows theIteratorcontract and throwsNoSuchElementExceptionat the end.
Expected output
for-each over the whole catalogue:
[supplier] fetching page 0
SKU-101
SKU-102
SKU-103
[supplier] fetching page 1
SKU-201
SKU-202
SKU-203
[supplier] fetching page 2
SKU-301
Stream, stopping after 4 items:
[supplier] fetching page 0
[supplier] fetching page 1
SKU-101, SKU-102, SKU-103, SKU-201
How it runs
- The
for-eachloop fetches page 0, then page 1 and page 2 as it needs them. - The stream asks for four items, so only pages 0 and 1 are fetched; page 2 is never requested.
- Each call to
iterator()starts a fresh walk, so the adapter can be reused.
Real-World Enterprise Example: Courier Tracking Port with Two Adapters
Problem: an order service tracks parcels with two couriers. One SDK returns status codes and local Indian time and throws a checked exception; the other returns a map with free-text status and epoch milliseconds. The service must see one consistent model.
import java.io.Serial;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
public class CarrierTrackingAdapterDemo {
// ---------- Domain side: the port (target) and its model ----------
enum DeliveryState { IN_TRANSIT, OUT_FOR_DELIVERY, DELIVERED }
record TrackingStatus(String trackingId, DeliveryState state, Instant updatedAt) { }
static final class TrackingUnavailableException extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
TrackingUnavailableException(String message, Throwable cause) { super(message, cause); }
}
interface ShipmentTracker {
boolean supports(String carrier);
TrackingStatus track(String trackingId);
}
// ---------- Vendor SDK 1: status codes and local IST timestamps ----------
static final class SwiftShipException extends Exception {
@Serial
private static final long serialVersionUID = 1L;
SwiftShipException(String message) { super(message); }
}
static final class SwiftShipSdk {
String[] lookup(String awb) throws SwiftShipException {
if (awb.startsWith("X")) throw new SwiftShipException("AWB not found: " + awb);
return new String[] {"OFD", "2026-11-02 09:15:00"}; // status code, IST local time
}
}
// ---------- Vendor SDK 2: a map with free-text status and epoch millis ----------
static final class GlobalCourierClient {
Map<String, Object> getShipment(String id) {
return Map.of("status", "Delivered to customer", "lastEventEpochMs", 1_793_620_800_000L);
}
}
// ---------- Adapters: one per vendor, each translating to the domain model ----------
static final class SwiftShipAdapter implements ShipmentTracker {
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final ZoneId IST = ZoneId.of("Asia/Kolkata");
private final SwiftShipSdk sdk;
SwiftShipAdapter(SwiftShipSdk sdk) { this.sdk = sdk; }
public boolean supports(String carrier) { return carrier.equals("SWIFTSHIP"); }
public TrackingStatus track(String trackingId) {
try {
String[] raw = sdk.lookup(trackingId);
DeliveryState state = switch (raw[0]) {
case "ITR" -> DeliveryState.IN_TRANSIT;
case "OFD" -> DeliveryState.OUT_FOR_DELIVERY;
case "DLV" -> DeliveryState.DELIVERED;
default -> throw new IllegalStateException("Unknown SwiftShip code " + raw[0]);
};
Instant updatedAt = LocalDateTime.parse(raw[1], FORMAT).atZone(IST).toInstant(); // IST -> UTC instant
return new TrackingStatus(trackingId, state, updatedAt);
} catch (SwiftShipException e) {
throw new TrackingUnavailableException("SwiftShip lookup failed", e); // vendor exception -> domain exception
}
}
}
static final class GlobalCourierAdapter implements ShipmentTracker {
private final GlobalCourierClient client;
GlobalCourierAdapter(GlobalCourierClient client) { this.client = client; }
public boolean supports(String carrier) { return carrier.equals("GLOBALCOURIER"); }
public TrackingStatus track(String trackingId) {
Map<String, Object> raw = client.getShipment(trackingId);
String status = ((String) raw.get("status")).toLowerCase();
DeliveryState state = status.startsWith("delivered") ? DeliveryState.DELIVERED
: status.contains("out for delivery") ? DeliveryState.OUT_FOR_DELIVERY
: DeliveryState.IN_TRANSIT;
Instant updatedAt = Instant.ofEpochMilli((Long) raw.get("lastEventEpochMs"));
return new TrackingStatus(trackingId, state, updatedAt);
}
}
// ---------- Application service: depends on the port only ----------
static final class OrderTrackingService {
private final List<ShipmentTracker> trackers;
OrderTrackingService(List<ShipmentTracker> trackers) { this.trackers = List.copyOf(trackers); }
String statusLine(String carrier, String trackingId) {
ShipmentTracker tracker = trackers.stream()
.filter(t -> t.supports(carrier))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No tracker for " + carrier));
try {
TrackingStatus status = tracker.track(trackingId);
return "%s %s at %s".formatted(status.trackingId(), status.state(), status.updatedAt().atOffset(ZoneOffset.UTC));
} catch (TrackingUnavailableException e) {
return trackingId + " unavailable: " + e.getCause().getMessage();
}
}
}
public static void main(String[] args) {
OrderTrackingService tracking = new OrderTrackingService(List.of(
new SwiftShipAdapter(new SwiftShipSdk()),
new GlobalCourierAdapter(new GlobalCourierClient())));
System.out.println(tracking.statusLine("SWIFTSHIP", "AWB-7781"));
System.out.println(tracking.statusLine("GLOBALCOURIER", "GC-55012"));
System.out.println(tracking.statusLine("SWIFTSHIP", "X-404"));
}
}
Important classes and methods
ShipmentTrackeris a port in hexagonal (ports and adapters) architecture: an interface owned by the domain.- Each adapter translates four things: the method call, the status vocabulary, the time format (to a UTC
Instant) and the error model (vendor exception to domain exception). OrderTrackingServicepicks an adapter throughsupports(). In Spring Boot, the adapters would be beans injected as aList<ShipmentTracker>.
Expected output
AWB-7781 OUT_FOR_DELIVERY at 2026-11-02T03:45Z
GC-55012 DELIVERED at 2026-11-02T12:00Z
X-404 unavailable: AWB not found: X-404
How it runs
- SwiftShip's
OFDbecomesOUT_FOR_DELIVERY, and 09:15 IST becomes 03:45 UTC. - GlobalCourier's "Delivered to customer" becomes
DELIVERED, and the epoch value becomes 12:00 UTC. - For
X-404, the SDK throws its checked exception, the adapter wraps it, and the service reports the tracking as unavailable.
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
| Aspect | Adapter | Facade | Decorator | Proxy | Bridge |
|---|---|---|---|---|---|
| Intent | Make an existing interface fit another | Simplify a whole subsystem | Add behaviour | Control access | Separate abstraction from implementation |
| Interface exposed | Different from the wrapped object | New, simpler interface | Same as the wrapped object | Same as the wrapped object | Abstraction's own interface |
| Wraps | Usually one object | Many objects | One object | One object | One implementor |
| Designed | After the fact | After the fact | Up front or later | Up front or later | Up 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.