Adapter
Making incompatible interfaces work together — object vs class adapters, wrapping third-party SDKs and legacy code, and the anti-corruption layer.
Intent: convert the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
Real-world analogy: a travel plug adapter. Your laptop charger (client) expects a UK socket; the wall (adaptee) is European. The adapter doesn't change either — it translates between them.
Example: one interface, many payment providers
Your app defines the interface it wants. Each provider's SDK has its own shape; adapters translate.
// Our interface (owned by our domain)
interface PaymentGateway {
PaymentResult charge(long amountCents, String currency, String token);
}
// Third-party SDK with an incompatible API (we can't change it)
class PayPalClient {
PayPalResponse createPayment(String amountDecimal, String currencyCode, String nonce) {...}
}
// Object adapter: wraps the SDK, implements our interface
class PayPalAdapter implements PaymentGateway {
private final PayPalClient client;
PayPalAdapter(PayPalClient client) { this.client = client; }
@Override
public PaymentResult charge(long amountCents, String currency, String token) {
String amount = BigDecimal.valueOf(amountCents, 2).toPlainString(); // 1999 -> "19.99"
PayPalResponse r = client.createPayment(amount, currency.toUpperCase(), token);
return r.getState().equals("approved")
? PaymentResult.success(r.getId())
: PaymentResult.failure(r.getFailureReason());
}
}class PaymentGateway(Protocol):
def charge(self, amount_cents: int, currency: str, token: str) -> PaymentResult: ...
class PayPalAdapter:
def __init__(self, client: "paypal.Client"):
self._client = client
def charge(self, amount_cents, currency, token):
resp = self._client.create_payment(
amount=f"{amount_cents / 100:.2f}",
currency_code=currency.upper(),
nonce=token,
)
if resp["state"] == "approved":
return PaymentResult.success(resp["id"])
return PaymentResult.failure(resp.get("failure_reason"))interface PaymentGateway {
charge(amountCents: number, currency: string, token: string): Promise<PaymentResult>;
}
class PayPalAdapter implements PaymentGateway {
constructor(private client: PayPalClient) {}
async charge(amountCents: number, currency: string, token: string) {
const r = await this.client.createPayment({
amount: (amountCents / 100).toFixed(2),
currencyCode: currency.toUpperCase(),
nonce: token,
});
return r.state === "approved"
? { ok: true as const, id: r.id }
: { ok: false as const, reason: r.failureReason };
}
}The adapter translates names, units, data shapes, error types and status codes — not just method names.
Object adapter vs class adapter
| Object adapter | Class adapter | |
|---|---|---|
| Mechanism | Composition: holds an adaptee instance | Inheritance: extends the adaptee and implements the target |
| Flexibility | Works with any subclass of the adaptee | Tied to one concrete class |
| Languages | Any | Needs multiple inheritance or interface + class |
| Preferred? | Yes, almost always | Rarely |
Where you see adapters
Arrays.asList()(array → List),InputStreamReader(byte stream → character reader).- ORMs and database drivers adapting vendor protocols to one API (JDBC, DB-API).
- Logging facades (SLF4J adapters for Log4j, JUL).
- React wrappers around imperative libraries (a chart library wrapped as a component).
- Ports and adapters (hexagonal architecture): the core defines ports (interfaces); adapters connect them to HTTP, databases and queues.
Anti-corruption layer
When integrating with a legacy system or external service whose model is messy, put a layer of adapters (and translators) at the boundary so its concepts don't leak into your domain. Your code speaks your language; only the adapter knows theirs. It also makes switching providers a matter of writing one new adapter.
- Adapter makes an existing class fit the interface your code expects.
- Prefer object adapters (composition).
- Translate units, shapes, errors and semantics, not just names.
- Wrap third-party SDKs behind your own interface — easier testing and switching.
- At system boundaries, adapters form an anti-corruption layer.