Convert the interface of an existing class into the interface its clients expect, so classes with incompatible interfaces can work together without changing either of them.
Adapter is the pattern you reach for when two pieces of code are each fine on their own but disagree about how they talk. Most of the time one side is code you cannot or should not change: a vendor SDK, a legacy module, a generated client. You write a small class that speaks your interface on the outside and the foreign interface on the inside. This guide follows one invented case: a pharmacy chain moving its prescription-ready text messages to a new SMS vendor without touching the code that sends them. Interviewers like Adapter because it tests whether you can separate your domain from someone else's API, and whether you can say where the translation belongs.
The problem
A situation where the obvious design starts to hurt.
Greenleaf Pharmacy runs 40 stores and sends about 12,000 text messages a day telling patients their prescription is ready. The notification code depends on one small interface, SmsSender, with a single method: send(phoneE164, text) returns a message id string and throws SmsDeliveryError on failure. Phone numbers are stored in E.164 format, like +447700900123.
Procurement has signed a cheaper contract with a vendor called TextBolt. Its SDK looks nothing like SmsSender. The method is transmit(countryCode, localNumber, body): the country code is a separate integer, the number has no plus sign or country prefix, and instead of throwing it returns a result object with an ok flag, a numeric ticket and an optional error code.
The obvious fix is to edit every call site: the prescription notifier, the refill reminder job and the delivery-slot confirmations. That spreads TextBolt's quirks through the codebase, means three places to fix if TextBolt changes its SDK, and makes switching vendors again just as painful. Editing the SDK itself is not an option; it is vendor code that gets replaced on every upgrade.
The solution
What the pattern proposes.
Write one class, TextBoltSmsAdapter, that implements SmsSender and holds a reference to a TextBoltClient. When the notifier calls send("+447700900123", text), the adapter splits the number into country code 44 and local number 7700900123, calls transmit, checks the ok flag, throws SmsDeliveryError if TextBolt rejected the message, and otherwise returns an id built from the ticket, such as tb-9001.
The notifier never learns that TextBolt exists. It is still constructed with an SmsSender, and the only change in the application is the line that wires dependencies together: pass a TextBoltSmsAdapter instead of the old sender.
All knowledge about the vendor lives in one file. If TextBolt adds a required field, renames a method or changes its error codes, you edit the adapter. If Greenleaf switches vendors again next year, you write another adapter and leave the rest of the system alone.
An everyday analogy
The same idea, outside software.
Think of a sign language interpreter at a press conference. The speaker talks the way they always do, and the deaf audience watches signing the way they always do. Neither side learns the other's language or changes how it communicates. The interpreter listens in one form and produces the same meaning in another, sometimes restructuring sentences because the grammar differs. Swap in a different interpreter for a different language and the speaker's speech stays exactly the same.
Structure
The pieces and how they relate.
Participants
- Target (SmsSender)
- The interface your code already depends on. It is defined in your terms: E.164 numbers in, a string id out, exceptions on failure.
- Client (PrescriptionNotifier)
- Code that uses the Target. It is built against
SmsSenderand is unaware which vendor sits behind it. - Adaptee (TextBoltClient)
- The existing class with a useful but incompatible interface. Here it is a third-party SDK you cannot change.
- Adapter (TextBoltSmsAdapter)
- Implements the Target and wraps an Adaptee instance. Translates arguments, return values and error conventions in both directions.
Pseudocode
The solution to the scenario, language-neutral.
interface SmsSender
method send(phoneE164, text): string
// vendor SDK, not ours
class TextBoltClient
method transmit(countryCode: int, localNumber, body): TransmitResult
class TextBoltSmsAdapter implements SmsSender
field client: TextBoltClient
const SUPPORTED_CODES = ["353", "44"]
method send(phoneE164, text)
(code, local) = splitNumber(phoneE164)
result = client.transmit(code, local, text)
if not result.ok
throw SmsDeliveryError(result.error)
return "tb-" + result.ticket
method splitNumber(phone)
if phone does not start with "+" then throw SmsDeliveryError
digits = phone without "+"
for code in SUPPORTED_CODES
if digits starts with code
return (toInt(code), digits after code)
throw SmsDeliveryError("unsupported country")
class PrescriptionNotifier
field sms: SmsSender
method notifyReady(phone, patient, store)
return sms.send(phone, "Hi " + patient + ", your prescription is ready at " + store + ".")
// composition root: the only place that knows about TextBolt
notifier = new PrescriptionNotifier(new TextBoltSmsAdapter(new TextBoltClient()))The code
The same solution in TypeScript, Python and PHP.
// Target: the interface Greenleaf's code depends on
interface SmsSender {
send(phoneE164: string, text: string): string;
}
class SmsDeliveryError extends Error {}
// Adaptee: simplified stand-in for the TextBolt vendor SDK
interface TransmitResult {
ok: boolean;
ticket: number;
error?: string;
}
class TextBoltClient {
private nextTicket = 9000;
transmit(countryCode: number, localNumber: string, body: string): TransmitResult {
if (body.length > 459) {
return { ok: false, ticket: 0, error: "BODY_TOO_LONG" };
}
this.nextTicket += 1;
console.log(`[TextBolt] +${countryCode} ${localNumber}: ${body}`);
return { ok: true, ticket: this.nextTicket };
}
}
// Adapter
class TextBoltSmsAdapter implements SmsSender {
private static readonly COUNTRY_CODES = ["353", "44"];
constructor(private readonly client: TextBoltClient) {}
send(phoneE164: string, text: string): string {
const { countryCode, localNumber } = this.splitNumber(phoneE164);
const result = this.client.transmit(countryCode, localNumber, text);
if (!result.ok) {
throw new SmsDeliveryError(`TextBolt rejected message: ${result.error}`);
}
return `tb-${result.ticket}`;
}
private splitNumber(phone: string): { countryCode: number; localNumber: string } {
if (!phone.startsWith("+")) {
throw new SmsDeliveryError(`Not an E.164 number: ${phone}`);
}
const digits = phone.slice(1);
for (const code of TextBoltSmsAdapter.COUNTRY_CODES) {
if (digits.startsWith(code)) {
return { countryCode: Number(code), localNumber: digits.slice(code.length) };
}
}
throw new SmsDeliveryError(`Unsupported country: ${phone}`);
}
}
// Client
class PrescriptionNotifier {
constructor(private readonly sms: SmsSender) {}
notifyReady(phone: string, patientName: string, storeName: string): string {
const text = `Hi ${patientName}, your prescription is ready at ${storeName}.`;
return this.sms.send(phone, text);
}
}
const notifier = new PrescriptionNotifier(new TextBoltSmsAdapter(new TextBoltClient()));
console.log(notifier.notifyReady("+447700900123", "Priya", "Greenleaf Camden"));
console.log(notifier.notifyReady("+353851234567", "Sean", "Greenleaf Galway"));
try {
notifier.notifyReady("+15550100", "Dana", "Greenleaf Camden");
} catch (e) {
console.log((e as Error).message);
}from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional
# Target: the interface Greenleaf's code depends on
class SmsSender(ABC):
@abstractmethod
def send(self, phone_e164: str, text: str) -> str: ...
class SmsDeliveryError(Exception):
pass
# Adaptee: simplified stand-in for the TextBolt vendor SDK
@dataclass
class TransmitResult:
ok: bool
ticket: int
error: Optional[str] = None
class TextBoltClient:
def __init__(self) -> None:
self._next_ticket = 9000
def transmit(self, country_code: int, local_number: str, body: str) -> TransmitResult:
if len(body) > 459:
return TransmitResult(ok=False, ticket=0, error="BODY_TOO_LONG")
self._next_ticket += 1
print(f"[TextBolt] +{country_code} {local_number}: {body}")
return TransmitResult(ok=True, ticket=self._next_ticket)
# Adapter
class TextBoltSmsAdapter(SmsSender):
COUNTRY_CODES = ("353", "44")
def __init__(self, client: TextBoltClient) -> None:
self._client = client
def send(self, phone_e164: str, text: str) -> str:
country_code, local_number = self._split_number(phone_e164)
result = self._client.transmit(country_code, local_number, text)
if not result.ok:
raise SmsDeliveryError(f"TextBolt rejected message: {result.error}")
return f"tb-{result.ticket}"
def _split_number(self, phone: str) -> tuple[int, str]:
if not phone.startswith("+"):
raise SmsDeliveryError(f"Not an E.164 number: {phone}")
digits = phone[1:]
for code in self.COUNTRY_CODES:
if digits.startswith(code):
return int(code), digits[len(code):]
raise SmsDeliveryError(f"Unsupported country: {phone}")
# Client
class PrescriptionNotifier:
def __init__(self, sms: SmsSender) -> None:
self._sms = sms
def notify_ready(self, phone: str, patient_name: str, store_name: str) -> str:
text = f"Hi {patient_name}, your prescription is ready at {store_name}."
return self._sms.send(phone, text)
if __name__ == "__main__":
notifier = PrescriptionNotifier(TextBoltSmsAdapter(TextBoltClient()))
print(notifier.notify_ready("+447700900123", "Priya", "Greenleaf Camden"))
print(notifier.notify_ready("+353851234567", "Sean", "Greenleaf Galway"))
try:
notifier.notify_ready("+15550100", "Dana", "Greenleaf Camden")
except SmsDeliveryError as e:
print(e)<?php
declare(strict_types=1);
// Target: the interface Greenleaf's code depends on
interface SmsSender
{
public function send(string $phoneE164, string $text): string;
}
class SmsDeliveryError extends RuntimeException {}
// Adaptee: simplified stand-in for the TextBolt vendor SDK
final class TransmitResult
{
public function __construct(
public readonly bool $ok,
public readonly int $ticket,
public readonly ?string $error = null,
) {}
}
class TextBoltClient
{
private int $nextTicket = 9000;
public function transmit(int $countryCode, string $localNumber, string $body): TransmitResult
{
if (strlen($body) > 459) {
return new TransmitResult(false, 0, 'BODY_TOO_LONG');
}
$this->nextTicket += 1;
echo "[TextBolt] +{$countryCode} {$localNumber}: {$body}\n";
return new TransmitResult(true, $this->nextTicket);
}
}
// Adapter
final class TextBoltSmsAdapter implements SmsSender
{
private const COUNTRY_CODES = ['353', '44'];
public function __construct(private readonly TextBoltClient $client) {}
public function send(string $phoneE164, string $text): string
{
[$countryCode, $localNumber] = $this->splitNumber($phoneE164);
$result = $this->client->transmit($countryCode, $localNumber, $text);
if (!$result->ok) {
throw new SmsDeliveryError("TextBolt rejected message: {$result->error}");
}
return "tb-{$result->ticket}";
}
/** @return array{int, string} */
private function splitNumber(string $phone): array
{
if (!str_starts_with($phone, '+')) {
throw new SmsDeliveryError("Not an E.164 number: {$phone}");
}
$digits = substr($phone, 1);
foreach (self::COUNTRY_CODES as $code) {
if (str_starts_with($digits, $code)) {
return [(int) $code, substr($digits, strlen($code))];
}
}
throw new SmsDeliveryError("Unsupported country: {$phone}");
}
}
// Client
final class PrescriptionNotifier
{
public function __construct(private readonly SmsSender $sms) {}
public function notifyReady(string $phone, string $patientName, string $storeName): string
{
$text = "Hi {$patientName}, your prescription is ready at {$storeName}.";
return $this->sms->send($phone, $text);
}
}
$notifier = new PrescriptionNotifier(new TextBoltSmsAdapter(new TextBoltClient()));
echo $notifier->notifyReady('+447700900123', 'Priya', 'Greenleaf Camden') . "\n";
echo $notifier->notifyReady('+353851234567', 'Sean', 'Greenleaf Galway') . "\n";
try {
$notifier->notifyReady('+15550100', 'Dana', 'Greenleaf Camden');
} catch (SmsDeliveryError $e) {
echo $e->getMessage() . "\n";
}When to use it
Situations where it pays off.
You want to use an existing class, often a third-party SDK, but its interface does not match the one the rest of your code relies on.
The adapter absorbs the mismatch in one place, so your domain code keeps its own vocabulary and does not import vendor types.
You expect to swap vendors or run two providers side by side, for example TextBolt in the UK and another gateway elsewhere.
Each provider gets its own adapter behind the same interface, and choosing one becomes a wiring decision instead of an edit across the codebase.
You are integrating a legacy module you are not allowed or not ready to refactor.
An adapter lets new code depend on a clean interface today while the legacy internals stay untouched until you can replace them.
You want to unit test code that talks to an external service.
Because the client depends on your interface rather than the SDK, tests can pass a fake
SmsSenderwithout mocking vendor classes.
How to implement it
Steps to introduce it in existing code.
Define the Target interface from the client's point of view: the method names, argument types and error behaviour your code wants, not what the vendor offers.
List every difference between the Target and the Adaptee: argument shapes (one E.164 string versus country code plus local number), return types (string id versus result object) and error style (exceptions versus status flags).
Create the adapter class, implement the Target interface and accept the Adaptee through the constructor so it can be replaced or faked.
Implement each Target method by translating inputs, calling the Adaptee, and translating outputs and failures back into your own types and exceptions.
Keep vendor-specific types inside the adapter. Nothing it returns or throws should be a TextBolt class.
Change only the composition root to construct the adapter, and add tests for the translation rules such as number splitting and error mapping.
Pros and cons
What you gain and what you pay.
Pros
- Single Responsibility: the translation between your model and the vendor's lives in one class instead of being scattered across call sites.
- Open/Closed: you can add a new provider by writing a new adapter without modifying existing client code.
- Client code stays independent of the SDK, which keeps vendor upgrades and vendor switches contained.
- Easy to test: clients take a fake Target in tests, and the adapter itself can be tested against a stubbed Adaptee.
Cons
- Adds a class and a layer of indirection, which is unjustified if you control both sides and could simply align the interfaces.
- Mismatches in capability cannot be hidden forever: if the vendor lacks a feature your interface promises, the adapter has to emulate it or fail.
- A thin adapter over a large SDK can grow into a second, hand-maintained API that must track every vendor release.
Relations with other guides
Patterns it's often confused or combined with.
- Facade Pattern: One Simple Entry Point to a Messy Subsystem
Facade defines a new, simpler interface over a whole subsystem; Adapter makes one existing object fit an interface that already exists. An adapter usually wraps one class, a facade often coordinates several.
- Bridge Pattern: Split Abstraction from Implementation
Bridge is designed up front so abstraction and implementation can vary independently. Adapter is usually applied after the fact to make classes that were never meant to cooperate work together.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
Decorator keeps the same interface and adds behaviour; Adapter changes the interface. You can decorate an adapter, for example adding logging around
SmsSender. - Proxy Pattern: Control Access with a Stand-In Object
Proxy offers the same interface as the object it wraps to control access to it; Adapter offers a different interface from the one it wraps.
- Circuit breaker: fail fast when a dependency is down
Resilience logic for a flaky vendor often wraps the adapter, so the breaker works in your own types and error classes rather than the SDK's.
- Middle Man
If an adapter only forwards calls unchanged because the interfaces already match, it has become a middle man and can be removed.
Common questions
Short answers to the usual doubts.
What is the difference between an object adapter and a class adapter?
An object adapter holds a reference to the adaptee and delegates to it, as TextBoltSmsAdapter does. A class adapter inherits from the adaptee and implements the target at the same time, which needs multiple inheritance or an adaptee that is safe to subclass. Object adapters are the default answer: they work with final SDK classes, can wrap any subclass of the adaptee, and keep the vendor's public methods off your interface.
Adapter or Facade: how do I explain the difference in an interview?
Ask who owns the interface. With Adapter, the client already has an interface it expects and you make an existing class conform to it. With Facade, you design a new, simpler entry point over a complicated subsystem. In the Greenleaf case SmsSender existed before TextBolt arrived, so wrapping TextBolt is an adapter, even if it also simplifies things.
Should the adapter do anything beyond translating calls?
Keep it to translation: argument shapes, return types, units, error conventions. Retries, rate limiting, caching and logging are separate concerns and fit better in decorators around SmsSender or in dedicated resilience components. Mixing them into the adapter makes it harder to test and harder to reuse when you add a second vendor.
Why not just pass TextBolt's result object back to the caller?
Because then every caller learns about ok, ticket and TextBolt error codes, and the vendor's model leaks into your domain. Mapping failures to your own SmsDeliveryError and returning a plain id means a future vendor only has to honour the same contract inside a new adapter.
Is it worth writing an adapter if I only have one vendor?
Often yes for external SDKs, because it gives you a test seam and keeps vendor types out of business code. It is not worth it when you own both sides and could simply rename a method, or when the SDK already matches your interface; then the adapter is a pass-through that adds nothing.