Adapter
Let objects with incompatible interfaces work together.
Use it when
You want to reuse an existing class whose interface doesn't match the one you need.
/**
* Adapter: plug a third-party payment SDK into existing checkout code.
*
* Real-world scenario: the checkout already works with any PaymentProcessor via
* pay(amount) in dollars. A new payment provider's SDK has a different method,
* takes cents and returns an object. We can't change the SDK, and we don't want
* to change the checkout, so an adapter translates between the two.
*/
// Target: the interface the checkout code expects.
interface PaymentProcessor {
/** Charge an amount in dollars and return a receipt message. */
pay(amount: number): string;
}
// An existing processor that already fits the interface.
class CardProcessor implements PaymentProcessor {
pay(amount: number): string {
return `Card charged $${amount.toFixed(2)}`;
}
}
// Adaptee: third-party code with an incompatible interface. We can't edit it.
class ExternalPaymentSDK {
sendPayment(amountCents: number, currency: string): { status: string; amount: string } {
return { status: "success", amount: `${amountCents} cents ${currency}` };
}
}
// Adapter: looks like a PaymentProcessor, calls the SDK underneath.
class ExternalPaymentAdapter implements PaymentProcessor {
private readonly sdk: ExternalPaymentSDK;
constructor(sdk: ExternalPaymentSDK) {
this.sdk = sdk;
}
pay(amount: number): string {
const cents = Math.round(amount * 100); // dollars -> cents
const response = this.sdk.sendPayment(cents, "USD");
return `External SDK charged ${response.amount} (${response.status})`;
}
}
// Client: knows only PaymentProcessor, so it works with both unchanged.
function checkout(processor: PaymentProcessor, amount: number): void {
console.log(processor.pay(amount));
}
function clientCode(): void {
checkout(new CardProcessor(), 49.99);
checkout(new ExternalPaymentAdapter(new ExternalPaymentSDK()), 49.99);
}
clientCode();
// Output:
// Card charged $49.99
// External SDK charged 4999 cents USD (success)How it works
| Role | Classes | What it does |
|---|---|---|
| Target | PaymentProcessor | The pay(amount) interface the checkout expects |
| Existing service | CardProcessor | Already implements the interface |
| Adaptee | ExternalPaymentSDK | Third-party code with a different method, units and return type |
| Adapter | ExternalPaymentAdapter | Implements PaymentProcessor and translates pay(amount) into SDK calls |
| Client | checkout() | Works with any PaymentProcessor, unchanged |