Adapter Pattern

An Adapter implements the interface your code already calls and, inside, translates each call into whatever a foreign class actually wants. The foreign class – a vendor SDK, a legacy service, a library you pulled in – does not change, and neither does your interface. The adapter is where the mismatch between them gets absorbed.

💡 Adaptee = the class you are wrapping and cannot change. Target = the interface your code already calls. An adapter implements the target and holds the adaptee.

Why this matters: half the machine-coding prompts involve something external – a payment gateway, an SMS provider, a storage client, a legacy pricing service. Interviewers watch whether your core classes compile against that external type or against an interface you own. A design where OrderService imports com.stripe.* fails the dependency-inversion question before you get to answer it, and it cannot be unit-tested without a network.


Prerequisites

  • Inheritance vs Composition – the object adapter holds its adaptee by composition, and knowing why that beats extending it is half this pattern
  • SOLID Principles – Adapter is how dependency inversion survives contact with code you did not write
  • Exception Handling – most of a real adapter’s work is translating one failure model into another

The Problem: the notification service that imports three SDKs

A service must send over SMS, email and push, and the three vendors agree on nothing. Twilio-style SMS takes two positional strings and returns a status string. The email SDK wants a builder-constructed MailMessage and throws a checked exception. The push SDK is asynchronous, takes a device token plus a JSON payload, and reports outcomes through callbacks.

Without adapters, the service becomes the integration layer:

import com.twilio.sdk.TwilioRestClient;   // vendor 1
import com.sendgrid.mail.SendGridClient;  // vendor 2, plus MailMessage and its exception
import io.fcm.push.FcmClient;             // vendor 3

public class NotificationService {
    private final TwilioRestClient twilio;
    private final SendGridClient sendGrid;
    private final FcmClient fcm;

    public void notify(Channel channel, User user, String subject, String body) {
        if (channel == Channel.SMS) {
            // Returns "sent:SM1a2b" or "failed:21610". Never throws.
            String status = twilio.messages().create(user.getPhone(), body);
            if (status.startsWith("failed")) log.warn("sms {}", status.substring(7));

        } else if (channel == Channel.EMAIL) {
            MailMessage msg = MailMessage.builder()
                    .to(user.getEmail()).subject(subject).html(body).build();
            try {
                sendGrid.dispatch(msg);
            } catch (SendGridException e) {
                throw new RuntimeException(e);      // because what else, here
            }

        } else if (channel == Channel.PUSH) {
            String payload = "{\"title\":\"" + subject + "\",\"body\":\"" + body + "\"}";
            fcm.sendAsync(user.getDeviceToken(), payload)
               .addCallback(ack -> log.info("accepted {}", ack.messageId()),
                            err -> log.error("push failed", err));
            // notify() has already returned by the time either of those runs
        }
    }
}

Three costs, and interviewers name all three:

  1. The service compiles against all three vendor SDKs. You cannot construct the class in a test without them, and a breaking change in any one of the three breaks this file.
  2. Adding WhatsApp means editing a working class. A fourth else if, a fourth field, a fourth import – a textbook open-closed violation.
  3. Three failure models leak into the caller. SMS failure is a string prefix, email failure is a checked exception, push failure is a callback that fires after notify returned. notify returns void because there is no single answer it could give, so the caller cannot ask “did it send, and should I try again?”

Class Diagram

classDiagram
    class NotificationChannel {
        <<interface>>
        +send(Notification) SendResult
        +type() ChannelType
    }
    class SendResult {
        +FailureKind failure
        +isRetryable() boolean
    }
    class SmsChannelAdapter {
        -TwilioRestClient twilio
        +send(Notification) SendResult
    }
    class EmailChannelAdapter {
        -SendGridClient sendGrid
        +send(Notification) SendResult
    }
    class PushChannelAdapter {
        -FcmClient fcm
        -Duration timeout
        +send(Notification) SendResult
    }
    class TwilioRestClient {
        +create(phone, text) String
    }
    class SendGridClient {
        +dispatch(MailMessage) String
    }
    class FcmClient {
        +sendAsync(token, json) Future
    }
    class NotificationService {
        -List~NotificationChannel~ channels
        +notify(ChannelType, Notification) SendResult
    }

    NotificationChannel <|.. SmsChannelAdapter
    NotificationChannel <|.. EmailChannelAdapter
    NotificationChannel <|.. PushChannelAdapter
    SmsChannelAdapter --> TwilioRestClient
    EmailChannelAdapter --> SendGridClient
    PushChannelAdapter --> FcmClient
    NotificationService --> NotificationChannel
    NotificationChannel ..> SendResult

The non-obvious part is the direction the arrows do not go: no vendor class points at NotificationChannel, because the vendors have never heard of it. SendResult is a type we own rather than a translation of any one vendor’s response, which is what makes these three adapters substitutable instead of three differently-shaped wrappers.


Real-World Example: Multi-Channel Notification Service

// ---- Target interface: our vocabulary, our failure model ----
public interface NotificationChannel {
    SendResult send(Notification notification);
    ChannelType type();
}

public record Recipient(String phone, String email, String deviceToken) { }
public record Notification(Recipient recipient, String subject, String body) { }
public enum FailureKind { NONE, TRANSIENT, PERMANENT, BAD_RECIPIENT }

public record SendResult(boolean ok, String id, FailureKind failure, String detail) {
    static SendResult sent(String id) { return new SendResult(true, id, FailureKind.NONE, ""); }
    static SendResult retry(String d) { return new SendResult(false, null, FailureKind.TRANSIENT, d); }
    static SendResult dead(String d)  { return new SendResult(false, null, FailureKind.PERMANENT, d); }
    static SendResult bad(String d)   { return new SendResult(false, null, FailureKind.BAD_RECIPIENT, d); }

    /** The one question a caller gets to ask about any vendor's failure. */
    public boolean isRetryable() { return failure == FailureKind.TRANSIENT; }
}

// ---- Adapter 1: vendor returns a status string and never throws ----
public final class SmsChannelAdapter implements NotificationChannel {
    // Throttle and carrier-queue codes are worth retrying; a blocked number is not.
    private static final Set<String> TRANSIENT = Set.of("20429", "30001", "30002");
    private final TwilioRestClient twilio;   // the adaptee, held by composition

    public SmsChannelAdapter(TwilioRestClient twilio) { this.twilio = twilio; }

    @Override public SendResult send(Notification n) {
        String phone = n.recipient().phone();
        if (phone == null || phone.isBlank()) return SendResult.bad("no phone");

        String status = twilio.messages().create(phone, n.body());
        if (status.startsWith("sent:")) return SendResult.sent(status.substring(5));

        String code = status.substring(status.indexOf(':') + 1);
        return TRANSIENT.contains(code) ? SendResult.retry("twilio " + code)
                                        : SendResult.dead("twilio " + code);
    }
    @Override public ChannelType type() { return ChannelType.SMS; }
}

// ---- Adapter 2: builder input, checked exceptions out ----
public final class EmailChannelAdapter implements NotificationChannel {
    private final SendGridClient sendGrid;

    public EmailChannelAdapter(SendGridClient sendGrid) { this.sendGrid = sendGrid; }

    @Override public SendResult send(Notification n) {
        String address = n.recipient().email();
        if (address == null) return SendResult.bad("no email");

        MailMessage message = MailMessage.builder()
                .to(address).subject(n.subject()).html(n.body()).build();
        try {
            return SendResult.sent(sendGrid.dispatch(message));
        } catch (SendGridRateLimitException e) {
            return SendResult.retry("sendgrid throttled");
        } catch (SendGridInvalidAddressException e) {
            return SendResult.bad(address);
        } catch (SendGridException e) {
            // Checked, and it stops here. No vendor type escapes this method.
            return SendResult.dead("sendgrid " + e.getStatusCode());
        }
    }
    @Override public ChannelType type() { return ChannelType.EMAIL; }
}

// ---- Adapter 3: async vendor behind a synchronous interface ----
public final class PushChannelAdapter implements NotificationChannel {
    private final FcmClient fcm;
    private final Duration timeout;
    private final ObjectMapper json = new ObjectMapper();

    public PushChannelAdapter(FcmClient fcm, Duration timeout) {
        this.fcm = fcm;
        this.timeout = timeout;
    }

    @Override public SendResult send(Notification n) {
        String token = n.recipient().deviceToken();
        if (token == null) return SendResult.bad("no device token");

        String payload;
        try {
            payload = json.writeValueAsString(Map.of("title", n.subject(), "body", n.body()));
        } catch (JsonProcessingException e) {
            return SendResult.dead("payload not serializable");
        }

        // Turning async into sync is this adapter's job, not the caller's.
        CompletableFuture<PushAck> pending = fcm.sendAsync(token, payload);
        try {
            return SendResult.sent(pending.get(timeout.toMillis(), MILLISECONDS).messageId());
        } catch (TimeoutException e) {
            pending.cancel(true);              // do not leak the in-flight call
            return SendResult.retry("fcm timeout after " + timeout);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();    // unwrap to the vendor's real error
            if (cause instanceof FcmUnregisteredTokenException) return SendResult.bad("stale token");
            if (cause instanceof FcmServerException) return SendResult.retry("fcm unavailable");
            return SendResult.dead("fcm " + cause.getClass().getSimpleName());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();  // restore the flag, then report
            return SendResult.retry("interrupted");
        }
    }
    @Override public ChannelType type() { return ChannelType.PUSH; }
}

// ---- The service: no vendor type appears anywhere in it ----
public class NotificationService {
    private final Map<ChannelType, NotificationChannel> channels;

    public NotificationService(List<NotificationChannel> adapters) {
        this.channels = adapters.stream().collect(toMap(NotificationChannel::type, a -> a));
    }

    public SendResult notify(ChannelType type, Notification n) {
        NotificationChannel channel = channels.get(type);
        if (channel == null) throw new UnsupportedChannelException(type);
        return channel.send(n);
    }
}
import json
from typing import Protocol
# SendResult and Failure have the same shape as the Java tab: a frozen dataclass
# carrying ok, provider_id, failure and a retryable property.

class NotificationChannel(Protocol):
    """Target interface. Structural -- no adapter below inherits from it."""
    channel: "ChannelType"
    def send(self, n: "Notification") -> SendResult: ...

class SmsChannelAdapter:
    channel = ChannelType.SMS
    _TRANSIENT = frozenset({"20429", "30001", "30002"})

    def __init__(self, twilio: "TwilioRestClient") -> None:
        self._twilio = twilio

    def send(self, n: "Notification") -> SendResult:
        if not n.recipient.phone:
            return SendResult(False, failure=Failure.BAD_ADDRESS, detail="no phone")
        status = self._twilio.create(n.recipient.phone, n.body)
        if status.startswith("sent:"):
            return SendResult(True, status[5:])
        code = status.split(":", 1)[1]
        kind = Failure.TRANSIENT if code in self._TRANSIENT else Failure.PERMANENT
        return SendResult(False, failure=kind, detail=f"twilio {code}")

class EmailChannelAdapter:
    channel = ChannelType.EMAIL

    def __init__(self, send_grid: "SendGridClient") -> None:
        self._send_grid = send_grid

    def send(self, n: "Notification") -> SendResult:
        message = (MailMessage.builder()
                   .to(n.recipient.email).subject(n.subject).html(n.body).build())
        try:
            return SendResult(True, self._send_grid.dispatch(message))
        except SendGridRateLimitError:
            return SendResult(False, failure=Failure.TRANSIENT, detail="throttled")
        except SendGridInvalidAddressError:
            return SendResult(False, failure=Failure.BAD_ADDRESS, detail=n.recipient.email)
        except SendGridError as exc:
            return SendResult(False, failure=Failure.PERMANENT, detail=f"sg {exc.status_code}")

class PushChannelAdapter:
    """Async adaptee, synchronous target. The future gets resolved in here."""
    channel = ChannelType.PUSH

    def __init__(self, fcm: "FcmClient", timeout_s: float = 3.0) -> None:
        self._fcm, self._timeout = fcm, timeout_s

    def send(self, n: "Notification") -> SendResult:
        payload = json.dumps({"title": n.subject, "body": n.body})
        pending = self._fcm.send_async(n.recipient.device_token, payload)
        try:
            return SendResult(True, pending.result(timeout=self._timeout).message_id)
        except FuturesTimeoutError:
            pending.cancel()
            return SendResult(False, failure=Failure.TRANSIENT, detail="fcm timeout")
        except FcmUnregisteredTokenError:
            return SendResult(False, failure=Failure.BAD_ADDRESS, detail="stale token")

# Structural typing means none of the three ever names NotificationChannel, and it
# also means that when the only mismatch is a method name, Python needs no adapter
# class at all -- a bound method already satisfies the Protocol. These classes earn
# their place for the translation inside send, not for the rename.
#include <string>
#include <unordered_set>
// SendResult, Failure and ChannelType as in the Java tab. SendResult::sent, ::retry,
// ::dead and ::bad are static factories over the same four fields.

class NotificationChannel {
public:
    virtual ~NotificationChannel() = default;
    virtual SendResult send(const Notification& n) = 0;
    virtual ChannelType type() const = 0;
};

// Object adapter. The adaptee is a reference here because this vendor client is
// shared across adapters and outlives them; hold it by value instead when it is a
// cheap movable handle. Either way it is a member, never a base class.
class SmsChannelAdapter : public NotificationChannel {
    TwilioRestClient& twilio_;
    static const std::unordered_set<std::string> kTransient;
public:
    explicit SmsChannelAdapter(TwilioRestClient& twilio) : twilio_(twilio) {}

    SendResult send(const Notification& n) override {
        if (n.recipient.phone.empty()) return SendResult::bad("no phone");
        const std::string status = twilio_.create(n.recipient.phone, n.body);
        if (status.rfind("sent:", 0) == 0) return SendResult::sent(status.substr(5));

        const std::string code = status.substr(status.find(':') + 1);
        return kTransient.count(code) > 0 ? SendResult::retry("twilio " + code)
                                          : SendResult::dead("twilio " + code);
    }
    ChannelType type() const override { return ChannelType::Sms; }
};
const std::unordered_set<std::string> SmsChannelAdapter::kTransient =
    {"20429", "30001", "30002"};

// The class-adapter form. Multiple inheritance makes it legal here and it is still
// usually wrong: this adapter now IS a TwilioRestClient, so the vendor's constructors
// and any base-class change are ours to absorb, and the adaptee can no longer be
// swapped for a fake at runtime -- which costs you every unit test.
class SmsClassAdapter : public NotificationChannel, private TwilioRestClient {
public:
    using TwilioRestClient::TwilioRestClient;

    SendResult send(const Notification& n) override {
        const std::string s = create(n.recipient.phone, n.body);  // inherited, not delegated
        return s.rfind("sent:", 0) == 0 ? SendResult::sent(s.substr(5))
                                        : SendResult::retry(s);
    }
    ChannelType type() const override { return ChannelType::Sms; }
};

An adapter is where the impedance mismatch gets paid for

An adapter is not a renaming layer. If SmsChannelAdapter.send were one line forwarding to twilio.create, the two interfaces were already compatible and the class is noise – delete it and call the vendor. Every adapter that earns its place contains the conversion nobody wants to think about:

  • Error-model translation. A status string, a checked exception and a callback all become one SendResult.
  • Sync against async. pending.get(timeout) plus a cancel on timeout, as in PushChannelAdapter.
  • Null against Optional. The vendor returns null for “not found”; your interface promised Optional.empty().
  • Units. Vendor cents against your Money, vendor epoch millis against your Instant.
  • Retry semantics. Which of the vendor’s error codes mean “try again” and which mean “stop”.

The practical rule is that last one. Collapse every one of the vendor’s transient failures into a single retryable signal, and do it in the adapter. isRetryable() above is that signal. The adapter is the only class that can know a Twilio 20429, an FCM UNAVAILABLE and a SendGrid 503 are the same situation – but it should not be the class that acts on it.

💡 Transient failure = one that may succeed if you make the same call again – a throttle, a timeout, a 5xx. Permanent and bad-recipient failures must not be retried, since retrying them burns quota for a guaranteed second failure. Learn more →

Object adapter versus class adapter

The object adapter holds an instance of the adaptee and delegates to it – every example above. The class adapter inherits from the adaptee instead, which needs multiple inheritance and so is only really expressible in C++. Prefer the object form essentially always: it works when the adaptee is final or has no public constructor, it lets you wrap a fake at runtime, and it does not make your type a subtype of the vendor’s. The class adapter’s one real advantage is overriding a protected adaptee method, which couples you to the vendor’s internals rather than its API.


Adapter vs Facade vs Decorator vs Proxy vs Bridge

All five put a class in front of another class. The question that separates them is who designed the interface you expose, and what you added behind it:

Pattern Intent Tell
Adapter Make a class you cannot change satisfy an interface that already exists Two interfaces are in play and you own exactly one of them
Facade Invent a new, simpler interface over a subsystem you own You designed the interface, so there was nothing to match
Decorator Add behaviour while keeping the same interface Wrapper and wrappee are the same type, and decorators stack
Proxy Control access to an object, same interface Same type as the subject, but what you added is a check, a cache or a lazy load
Bridge Separate an abstraction hierarchy from its implementation hierarchy Both hierarchies were designed together, up front – Bridge is a plan, Adapter is a repair

The practical overlap is Adapter and Facade, and it is real: NotificationService above is a Facade and the three classes underneath it are Adapters, in one stack. Decorator and Proxy are easy to rule out – if the wrapper’s type equals the wrapped type, it is one of those two.


When to Use vs When to Avoid

Use Adapter When Avoid When
A third-party SDK’s API does not match the interface your code calls You own both sides and can simply change one signature
Two or more vendors sit behind one capability in your domain The wrapper would forward every call unchanged, adding nothing
You need to unit-test code that talks to an external service You want a smaller API over classes you own – that is a Facade
A legacy class must participate in new polymorphic code The vendor is the only implementation forever and is already fakeable
The vendor’s failure model, units or threading model differ from yours The target interface genuinely cannot express what the adaptee needs

The characteristic failure mode is the adapter that grows business logic. Because SmsChannelAdapter is the only class holding a vendor, it becomes the convenient home for everything near that vendor: pick SMS when the user has no email, fall back to a second provider when Twilio is down, render the message template. Routing and vendor failover are decisions across channels, so they belong in NotificationService – the Facade that holds all the adapters and is the only object that can see more than one. Template rendering belongs higher still, in whatever constructs the Notification, since a rendered body is an input to sending rather than part of it. The test is one sentence: an adapter may only know about its own adaptee.


Interview Questions

  1. “Adapter vs Facade?” – Who designed the interface. An Adapter implements an interface that already existed and that you had to match, converting calls into a class you do not control; a Facade invents a new, simpler interface of your own design over a subsystem you own. A one-method Facade and an Adapter can be identical in shape, so the separating question is “was I handed this signature, or did I write it?”

  2. “What if the target interface genuinely cannot express something the adaptee needs?” – This is the leaky adapter problem, and there are two honest answers: widen the target interface deliberately, adding the capability as a first-class method that every adapter implements and accepting that some no-op, or admit the abstraction is wrong because these vendors are not interchangeable and let the caller depend on two interfaces. What you must not do is add a Map&lt;String, Object&gt; options parameter or a getUnderlyingClient() escape hatch – the caller then needs vendor knowledge to use the interface, so you have paid for the adapter and kept the coupling.

  3. “How do you test an adapter without calling the vendor?” – Hand-write a fake adaptee rather than mocking the vendor’s class, because a mock asserts what you believe the SDK does and a fake lets you encode what it actually does. Give the fake a way to produce each interesting response – "sent:SM1", "failed:21610", "failed:20429", a throw, a future that never completes – and the adapter’s tests become a table mapping vendor response to SendResult. Testing in machine coding covers the shared contract test that then runs every adapter against the same assertions.

  4. “Should you write adapters for a vendor you are certain you will never replace?” – Yes, but be honest about why: for testability, not portability. The portability argument is mostly a bluff, since replacing a payment gateway is a quarter of work and the adapter saves a small slice of it. The testability argument pays out daily – without the adapter, every test of every class that sends a notification needs the vendor’s client, so you either hit the network or mock a type you do not control.

  5. “Where does retry go – in the adapter or above it?” – Above it, with the adapter supplying only the classification. Retry inside SmsChannelAdapter gives you attempts you cannot see or budget, that fight the service’s own timeout, and that get reimplemented three ways once there are three vendors. Have the adapter return isRetryable() and let one policy object above the adapters own the attempt count, the backoff curve and the circuit breaker. The case worth naming out loud is a retry the SDK does internally and will not let you disable, because it multiplies silently against yours.


See It in Action

  • Notification Service – SmsChannelAdapter, EmailChannelAdapter and PushChannelAdapter behind one NotificationChannel
  • Payment Wallet – each gateway’s SDK wrapped so the ledger only ever knows PaymentGateway
  • Mini ORM – a JDBC ResultSet adapted into domain objects behind the repository interface