Adapter lets your code use a class whose interface does not match the one your code expects. You write a small class that implements your interface and translates each call into the other class's language: different method names, different argument shapes, different units, different results. The other class is usually one you cannot or should not change, such as a vendor SDK, a legacy module or a library. Your business code then depends only on the interface you own, so the foreign API stays in one place and swapping it out means writing one new adapter.
Think of it like
A travel plug adapter
Your laptop charger has a US plug and the hotel wall has a UK socket. You do not rewire the charger or the hotel; you put a small adapter between them that has UK pins on one side and a US socket on the other. The charger is your code, the socket shape it expects is your interface, the wall is the third-party class, and the plug adapter is the Adapter. When you travel to another country you buy another small adapter, and the charger never changes.
The problem
A shop's Checkout takes payments through a vendor called Acme, using Acme's SDK. The SDK is third-party code: you install it, you call it, you cannot edit it. Its API is not shaped like your app. Your prices are dollars, but charge() wants whole cents. Your code wants a simple receipt, but the SDK answers with its own status object. The quickest integration calls the SDK straight from Checkout. This is the Before version in the visualizer above.
// Vendor SDK: we cannot edit it
class AcmeSdk {
charge(cents: number) {
return { status: "ok", id: `A${cents}` };
}
}
class Checkout {
private orders = 0;
constructor(private sdk: AcmeSdk) {}
checkout(total: number): string {
const cents = Math.round(total * 100); // Acme wants cents
const res = this.sdk.charge(cents);
const r = res.status === "ok" ? `paid ${res.id}` : "failed";
this.orders++;
return `#${this.orders} ${r}`;
}
}
const shop = new Checkout(new AcmeSdk());
shop.checkout(12.5); // "#1 paid A1250"
shop.checkout(19.99); // "#2 paid A1999"It works. But Checkout now speaks Acme's language, and that has costs:
- Vendor details leak into business code. The dollars-to-cents conversion, the rounding (in floating point
19.99 × 100is1998.9999999999998, so forgettingMath.roundsends a fractional amount) and the meaning ofstatus: "ok"all sit in the class that holds your ordering rules. - Switching vendors edits
Checkout. When the business moves to Zeta, whose SDK has a different method, a different request shape and a different result, the class with the business rules is rewritten and re-tested. The visualizer's change request shows exactly this. - The leak spreads. Refunds, subscriptions and reports soon call the SDK too, each with its own copy of the conversion and the status check. Changing vendor then means finding every one of them.
- Hard to test. A unit test of
Checkoutneeds Acme's SDK, or a fake that mimics Acme's exact API, instead of a fake of a small interface you own.
The pattern
Intent: convert the interface of a class into another interface that clients expect, so classes that could not work together because of incompatible interfaces can.
- Target (
PaymentGateway) - The interface the client code expects and you own:
pay(amount): string, with the amount in dollars and a receipt string back. It is designed for your application, not copied from any vendor. - Client (
Checkout) - The code that needs the work done. It holds a
PaymentGatewayand callspay(). It never names a vendor class. - Adaptee (
AcmeSdk) - The existing class with the useful behavior and the wrong interface:
charge(cents)returning{ status, id }. You do not change it. - Adapter (
AcmeAdapter) - Implements the target and holds an adaptee. Each target call is translated into adaptee calls, and each adaptee result is translated back: dollars to cents on the way in, status object to receipt string on the way out.
This is the object adapter: the adapter has an adaptee in a field (composition) and implements the target interface. Checkout is coupled only to PaymentGateway, and the adapter is the only class that knows Acme exists. The adapter should translate and nothing more; your business rules stay in Checkout.
What the visualizer shows
- Class diagram:
Checkouton the left points at thePaymentGatewayinterface; below it,AcmeAdapterimplements that interface and points atAcmeSdkthrough itssdkfield (labelled adaptee). Whenshopcallspay,PaymentGatewaylights violet (it declares the method) whileAcmeAdapterlights amber (its code runs). - Objects at runtime:
shop : Checkoutwithgateway = adapter,adapter : AcmeAdapterwithsdk = sdk, andsdk : AcmeSdk. Watch the arguments change as the message passes through the adapter:pay(12.5)arrives in dollars and leaves ascharge(1250); the SDK returns{status: "ok", id: "A1250"}and the adapter hands"paid A1250"back toshop. - Sequence of calls: three lifelines in a row,
shop,adapter,sdk. Eachcheckoutcall becomespayand thencharge, and the returns come back the same way.
Press Play in the visualizer at the top of the page, or step with the arrow buttons: it really runs the classes in the code panel. The Before / With Adapter toggle switches between Checkout calling the SDK itself and the adapter version. Switch to Zeta applies the change request to whichever version is shown: changed classes get a badge (new class, or edited +9 −7), and the Change request panel beside the code counts what each version had to change. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Wire it up
With With Adapter selected, the client creates the vendor's
sdk, wraps it innew AcmeAdapter(sdk), and gives the adapter tonew Checkout(adapter).shop.gatewaynow points atadapter;shophas no idea a vendor SDK exists. - 2
Business code calls its own interface
The client calls
shop.checkout(12.5), andshopcallspay(12.5)on whatever is in itsgatewayfield.payis declared byPaymentGateway; the object is anAcmeAdapter, soAcmeAdapter.payruns. - 3
Translate the request
The adapter converts dollars to cents:
12.5 × 100is1250, and it callssdk.charge(1250). The method name, the unit and the argument are all Acme's. - 4
Translate the response
The SDK returns
{status: "ok", id: "A1250"}. The adapter maps it to the receipt string your interface promises,"paid A1250", and returns it toshop. - 5
Business logic continues
shopcounts the order (ordersbecomes1) and returns"#1 paid A1250"to the client. - 6
The tricky amount
shop.checkout(19.99)goes the same way. This time19.99 × 100is1998.9999999999998in floating point, and the adapter rounds it to1999. That detail lives in exactly one class. The order returns"#2 paid A1999". - 7
Switch to Zeta (change request)
With Switch to Zeta applied, the client builds
new ZetaAdapter(new ZetaSdk())instead.ZetaAdapter.payformats12.5as the string"12.50", callssubmit({ amount, currency }), and maps Zeta's{ok: true, ref: "Z-12.50"}to"paid Z-12.50".Checkoutruns the same code and returns"#1 paid Z-12.50".
Before and after
Without the pattern
Checkoutholds the vendor SDK and calls it directly- Unit conversion and status mapping live in business code
- Switching vendors rewrites
Checkout's payment code - Tests of
Checkoutneed the SDK or a fake of its exact API - One class fewer; fine for a quick prototype
With Adapter
Checkoutdepends onPaymentGateway, an interface you own- Each vendor's quirks live in its own small adapter
- Switching vendors adds an adapter;
Checkoutis untouched Checkoutis tested with a three-line fake gateway- Two vendors can even run side by side (by region, or during a migration)
| Change request: switch to Zeta | Before | With Adapter |
|---|---|---|
| Existing classes edited | 1 (Checkout) | 0 |
| New classes | 1 (ZetaSdk) | 2 (ZetaAdapter, ZetaSdk) |
| Classes removed | 1 (AcmeSdk) | 2 (AcmeAdapter, AcmeSdk) |
| Lines changed in existing classes | 16 (+9 −7) | 0 |
Read the numbers honestly. ZetaSdk counts as a new class in both versions, but it is the vendor's code: you install it, you do not write it. The real work is 16 changed lines inside Checkout in one version, and one new ZetaAdapter class (16 lines) in the other. The adapter version also removes more, because the old AcmeAdapter is deleted along with Acme's SDK. What matters is where the change lands: in the class with your business rules, or in a class whose only job is to talk to Acme or Zeta. In both versions the client wiring changes too, because something has to say "use Zeta".
Variations
Object adapter vs class adapter
The Gang of Four describe two forms. The object adapter (above) holds the adaptee in a field. The class adapter inherits from the adaptee and implements the target, so the adapter is an adaptee. GoF wrote it with C++ multiple inheritance (publicly from the target, privately from the adaptee). Java and TypeScript can express it only when the target is an interface: class AcmeClassAdapter extends AcmeSdk implements PaymentGateway.
| Object adapter (composition) | Class adapter (inheritance) | |
|---|---|---|
| Works with subclasses of the adaptee | Yes: pass any AcmeSdk subclass, chosen at runtime | No: welded to the one class it extends |
Adaptee is final / sealed, or you only get an instance from a factory | Fine | Impossible |
| Adaptee's own methods visible to clients | No, hidden behind the field | Yes with public inheritance (charge() leaks); C++ private inheritance hides them |
| Override some adaptee behavior | Only through the adaptee's public API | Yes, directly |
| Extra object and one extra call | Yes, usually negligible | No |
| Languages | All | C++ (multiple inheritance); Java, C#, TypeScript when the target is an interface |
Two-way adapters
A two-way adapter implements both interfaces, so it can be used wherever either one is expected. It is useful during a migration, when old code calls the legacy interface and new code calls the new one, and both must reach the same object.
interface LegacyLogger { write(level: number, msg: string): void; }
interface Logger { info(msg: string): void; error(msg: string): void; }
class TwoWayLogger implements Logger, LegacyLogger {
constructor(private readonly out: (line: string) => void) {}
info(msg: string) { this.write(1, msg); }
error(msg: string) { this.write(3, msg); }
write(level: number, msg: string) {
this.out(`[${level >= 3 ? "ERROR" : "INFO"}] ${msg}`);
}
}Adapting functions: callbacks to promises
An adapter does not have to be a class. A function that changes how another function is called is an adapter too. The classic case is converting Node's error-first callback style into a promise so it fits async/await. Node ships this adapter as util.promisify, and util.callbackify goes the other way.
type Callback<T> = (err: Error | null, value?: T) => void;
function promisify<A extends unknown[], T>(
fn: (...args: [...A, Callback<T>]) => void,
): (...args: A) => Promise<T> {
return (...args) =>
new Promise<T>((resolve, reject) =>
fn(...args, (err, value) =>
err ? reject(err) : resolve(value as T)),
);
}
// Node's built-in version of the same adapter:
import { promisify as nodePromisify } from "node:util";
import { readFile } from "node:fs";
const read = nodePromisify(readFile);
// const text = await read("notes.txt", "utf8");The architectural version: anti-corruption layer
Scale the idea up from one class to a whole integration and you get the anti-corruption layer from Eric Evans's Domain-Driven Design: a layer of adapters (often behind a Facade) between your model and a legacy or external system, translating its concepts into yours so its model does not corrupt yours. It is common in migrations such as Strangler Fig, where new services must talk to the old system for a while. The "adapters" of hexagonal architecture (ports and adapters, see Layered, Hexagonal & Clean Architecture) are the same pattern again: the domain defines ports (target interfaces), and adapters plug databases, queues and HTTP APIs into them.
In real code
| Where | Adaptee | Target it is adapted to |
|---|---|---|
Java Arrays.asList(array) | A plain array | The List interface. The list is a fixed-size view backed by the array: set writes through, add and remove throw UnsupportedOperationException |
Java InputStreamReader | An InputStream (bytes) | A Reader (characters), decoding with a charset. Its Javadoc calls it "a bridge from byte streams to character streams", but in pattern terms it is an adapter |
Java Collections.enumeration(c) | Any Collection | The legacy Enumeration interface that old APIs still accept. Since Java 9, Enumeration.asIterator() adapts the other way |
Node.js util.promisify(fn) | A function taking an error-first callback | A function returning a Promise; util.callbackify reverses it |
Python io.TextIOWrapper | A binary buffered stream | A text stream with read() and readline() returning str |
C++ std::stack, std::queue, std::priority_queue | A sequence container (std::deque or std::vector by default) | A stack, queue or heap interface. The standard calls them container adapters |
| Database drivers and ORM dialects | Each database's wire protocol and SQL dialect | One standard API (JDBC in Java, DB-API in Python, an ORM's query interface) that application code is written against |
When to use it, and when not to
Reach for Adapter when
- You must use a class whose interface does not fit, and you cannot change it
- A third-party API, unit system or data format would otherwise leak into business code
- You may switch providers, or run two at once
- You want to test business code against a small fake of an interface you own
- Legacy and new code must work together during a migration
Skip it when
- You own both sides: change one of them to fit instead
- The interfaces already match, or differ by one trivial rename
- The SDK is used in one tiny script that will not outlive the vendor
- You would need to wrap a huge API one-to-one, with no translation (that is just a mirror; consider a narrower Facade)
Adapter vs similar patterns
| Pattern | Interface the client sees | Purpose | When it is designed |
|---|---|---|---|
| Adapter | A different one: the client's target, not the adaptee's | Make an existing class fit code that expects another interface | After the fact, to join things that already exist |
| Facade | A new, simpler one over many classes | Hide a complicated subsystem behind one entry point | Whenever a subsystem is too complex to use directly |
| Decorator | The same one as the wrapped object | Add behavior (logging, caching, retries); wrappers stack | Any time; transparent to the client |
| Proxy | The same one as the real object | Control access: lazy loading, permissions, remote calls | Any time; the client thinks it has the real object |
| Bridge | The abstraction's own interface | Split an abstraction from its implementations so both vary independently | Up front, by design, before the classes exist |
Implementation
The visualizer's scenario as a complete program: Checkout depends on a PaymentGateway interface the app owns; AcmeAdapter and ZetaAdapter each translate it to a vendor SDK with a different method, argument shape, unit and result. Switching vendors is a different adapter and no change to Checkout. The SDKs are small stand-ins for real vendor libraries.
from dataclasses import dataclass
from typing import Protocol
class PaymentGateway(Protocol):
"""The interface our application owns; Checkout depends only on it."""
def pay(self, amount: float) -> str: ...
# ---- Vendor SDKs: third-party code we cannot edit ----
@dataclass(frozen=True)
class AcmeResult:
status: str
id: str
class AcmeSdk:
def charge(self, cents: int) -> AcmeResult:
if cents <= 0:
return AcmeResult("declined", "")
return AcmeResult("ok", f"A{cents}")
class ZetaSdk:
def submit(self, req: dict[str, str]) -> dict[str, object]:
ok = float(req["amount"]) > 0
return {"ok": ok, "ref": f"Z-{req['amount']}"}
# ---- Adapters: one per vendor, each implements our interface ----
class AcmeAdapter:
def __init__(self, sdk: AcmeSdk) -> None:
self._sdk = sdk
def pay(self, amount: float) -> str:
cents = round(amount * 100) # dollars to cents
res = self._sdk.charge(cents)
return f"paid {res.id}" if res.status == "ok" else "failed"
class ZetaAdapter:
def __init__(self, sdk: ZetaSdk) -> None:
self._sdk = sdk
def pay(self, amount: float) -> str:
res = self._sdk.submit(
{"amount": f"{amount:.2f}", "currency": "USD"}
)
return f"paid {res['ref']}" if res["ok"] else "failed"
# ---- Business code: knows only PaymentGateway ----
class Checkout:
def __init__(self, gateway: PaymentGateway) -> None:
self._gateway = gateway
self._orders = 0
def checkout(self, total: float) -> str:
receipt = self._gateway.pay(total)
self._orders += 1
return f"#{self._orders} {receipt}"
if __name__ == "__main__":
acme_shop = Checkout(AcmeAdapter(AcmeSdk()))
print(acme_shop.checkout(12.5)) # #1 paid A1250
print(acme_shop.checkout(19.99)) # #2 paid A1999
# Switching vendors: a new adapter, no change to Checkout.
zeta_shop = Checkout(ZetaAdapter(ZetaSdk()))
print(zeta_shop.checkout(12.5)) # #1 paid Z-12.50
print(zeta_shop.checkout(19.99)) # #2 paid Z-19.99Key takeaways
- Adapter implements the interface your code expects and translates each call (names, arguments, units) and each result into the language of a class you cannot change.
- Own the target interface: write it in your domain's terms, so every vendor or legacy module is made to fit your code, not the other way round.
- In the visualizer's "Switch to Zeta" request, the adapter version edits 0 existing classes; without it,
Checkoutitself changes by 16 lines. - Prefer the object adapter (composition): it works with subclasses and instances you did not create, and hides the adaptee's API. The class adapter (inheritance) is rigid and can leak the adaptee's methods.
- Adapters also come as functions (
util.promisify) and as whole layers (the anti-corruption layer, the adapters of hexagonal architecture). - Adapter changes an interface after the fact. Decorator and Proxy keep the same interface, Facade simplifies many into one, and Bridge separates abstraction and implementation by design.
Common pitfalls
- Copying the vendor's API into your target interface (
charge(cents)because Acme had it). The next vendor will not fit, and the leak is back one level up. - Putting business logic in the adapter. Discounts, order rules and retry policies belong elsewhere; an adapter that decides things is hard to replace when the vendor changes.
- Translating only the happy path. Map the vendor's errors, status codes and exceptions to your own error types too, or vendor exception classes will leak into callers.
- Leaky conversions: forgetting rounding (
19.99 × 100is not1999in floating point), currency, time zones or character encodings. These are exactly the details the adapter exists to get right, so test it on its own. - Wrapping a huge API one-to-one "just in case". Adapt the operations you use: a small target interface (see Interfaces & Abstract Classes) is easy to implement for the next vendor and easy to fake in tests, while an eighty-method mirror is costly to keep up to date.
Interview tips
- In LLD rounds, whenever the problem mentions an external payment, SMS, map or storage provider, define your own interface first and say "each provider gets an adapter". It shows you isolate third-party APIs and makes switching providers a one-class change.
- Be ready to explain object vs class adapter, and to say why the object adapter is usually preferred (composition over inheritance, works with final classes and subclasses, hides the adaptee).
- Expect "Adapter vs Decorator vs Proxy vs Facade". Answer with the interface: Adapter changes it, Decorator and Proxy keep it, Facade simplifies a whole subsystem. Then add Bridge: designed up front, while Adapter is a retrofit.
Real-world applications
- Payment, email, SMS and push-notification providers behind one interface each, so a provider can be swapped or two can run at once.
- Cloud storage clients (S3, Google Cloud Storage, Azure Blob) behind a small
BlobStoreinterface. - Wrapping legacy modules so new code can call them through modern interfaces during a migration.
- Converting callback-based APIs to promises (
util.promisify) and byte streams to character streams (InputStreamReader). - Database drivers and ORM dialects that present one API over many databases.
- Test doubles: a fake that implements your target interface replaces the whole vendor in unit tests.
Test yourself
What problem does the Adapter pattern solve?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.