Patterns for structure · Chapter 10

Adapter pattern

Make a class with the wrong interface fit the one your code expects by wrapping it in a small translator. Java and Python code, and how Adapter differs from Decorator, Proxy and Facade.

BeginnerInterview priority: High35 min
On this page
  1. The problem: a library that doesn't fit
  2. The idea: a translator in between
  3. Build it step by step
  4. Small adapters in modern code
  5. Adapter, Decorator, Proxy, Facade: how they differ
  6. When not to use it
  7. In the interview
  8. Quiz

The problem: a library that doesn't fit

A weather app is built around one interface. Every screen, every test and every cache calls WeatherSource.getTempC(city). Now the company wants to switch to a cheaper provider, and its library looks nothing like that: the method is fetch(lat, lon), it wants coordinates instead of a city name, and it answers in Fahrenheit.

Two interfaces that don't fit

  1. Your weather app is built around one interface: WeatherSource.getTempC(city). Now you want a cheaper provider, but its library looks completely different: fetch(lat, lon), and it answers in Fahrenheit.
  2. You can’t edit their library: it isn’t yours. And you don’t want to rewrite every screen of your app around their odd method. Like a foreign plug, the two sides just don’t fit.

There are two tempting fixes, and both hurt:

  • Change the app to call fetch(lat, lon) everywhere. Twenty screens now depend on one vendor's method names and units. Switching vendor again next year means editing all twenty again.
  • Change the library. You can't: it's a compiled third-party package, and even if you forked it you'd have to re-apply your edits on every upgrade.

What you want is to keep both sides exactly as they are and put the translation in one place.

The idea: a translator in between

An adapter is a small class that implements the interface your code expects, holds the other object inside, and translates each call: arguments on the way in, results and errors on the way out. The app never learns that a different provider exists.

The adapter implements your interface and wraps theirs

  1. An adapter is a small class in between. It implements your interface, holds the provider’s object inside, and translates each call: city to coordinates on the way in, Fahrenheit to Celsius on the way out.
RoleIn this exampleResponsibility
TargetWeatherSourceThe interface the client code is written against
ClientWeatherScreenUses only the target
AdapteeNewWeatherCoThe existing class with the incompatible interface
AdapterNewWeatherAdapterImplements the target, wraps the adaptee, translates

Build it step by step

1. Keep the target interface you already have. It describes what your app needs, in your words and units.

2. Wrap the adaptee. The adapter receives the vendor object in its constructor (this is the object adapter, using composition).

3. Translate all three directions: inputs (city to coordinates), outputs (Fahrenheit to Celsius) and errors (the vendor's exceptions to yours). The error part is the one people forget; without it, vendor exception types leak into every caller.

4. Wire it up in one place, so the client receives a WeatherSource and never sees the adapter's class name.

import java.util.*;

// --- Our side: the interface the whole app is written against (the target) ---
interface WeatherSource {
    double getTempC(String city);    // throws WeatherUnavailableException
}

class WeatherUnavailableException extends RuntimeException {
    WeatherUnavailableException(String msg, Throwable cause) { super(msg, cause); }
}

class WeatherScreen {                 // the client: knows only WeatherSource
    private final WeatherSource source;
    WeatherScreen(WeatherSource source) { this.source = source; }
    String headline(String city) {
        return city + ": " + Math.round(source.getTempC(city) * 10) / 10.0 + " °C";
    }
}

// --- Their side: a library we cannot change (the adaptee) ---
class NewWeatherCo {
    double fetch(double lat, double lon) {            // answers in Fahrenheit
        if (Double.isNaN(lat)) throw new IllegalArgumentException("bad coordinates");
        return 71.6;
    }
}

record LatLon(double lat, double lon) {}

class CityDirectory {
    private final Map<String, LatLon> known = Map.of("Lisbon", new LatLon(38.72, -9.14));
    Optional<LatLon> lookup(String city) { return Optional.ofNullable(known.get(city)); }
}

// --- The adapter: implements OUR interface, wraps THEIR object ---
class NewWeatherAdapter implements WeatherSource {
    private final NewWeatherCo api;
    private final CityDirectory cities;

    NewWeatherAdapter(NewWeatherCo api, CityDirectory cities) {
        this.api = api;
        this.cities = cities;
    }

    @Override
    public double getTempC(String city) {
        LatLon p = cities.lookup(city)                              // translate the input
            .orElseThrow(() -> new WeatherUnavailableException("Unknown city: " + city, null));
        try {
            double f = api.fetch(p.lat(), p.lon());
            return (f - 32) * 5 / 9;                                // translate the output
        } catch (IllegalArgumentException e) {                      // translate their errors
            throw new WeatherUnavailableException("Provider rejected " + city, e);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        WeatherSource source = new NewWeatherAdapter(new NewWeatherCo(), new CityDirectory());
        WeatherScreen screen = new WeatherScreen(source);
        System.out.println(screen.headline("Lisbon"));   // Lisbon: 22.0 °C
        try {
            screen.headline("Atlantis");
        } catch (WeatherUnavailableException e) {
            System.out.println("Shown to user: " + e.getMessage());
        }
    }
}

Switching vendors is now one class

When the old provider is retired, nothing in WeatherScreen changes. You write NewWeatherAdapter, change one line where the WeatherSource is created, and run the same tests. Both adapters can even live side by side behind a feature flag while you compare their answers. This is dependency inversion at work: the app owns the interface and the vendors are plugged in underneath it.

Object adapter or class adapter?

The version above is an object adapter: it has the adaptee. The alternative is a class adapter, which inherits from the adaptee and implements the target (class NewWeatherAdapter extends NewWeatherCo implements WeatherSource).

Object adapter (composition)Class adapter (inheritance)
Works withAny adaptee, including final classes and interfacesOnly non-final classes
ExposesOnly the target's methodsThe target's methods and every public adaptee method
Swap the adaptee at run time or in testsYes, pass a different object or a mockNo, it is fixed at compile time
Use whenAlmost alwaysRarely: you must override a protected adaptee method

Prefer the object adapter. A class adapter leaks the vendor's whole API to anyone holding the adapter, which defeats the point.

Small adapters in modern code

An adapter doesn't need a class when the target is a single method. A lambda or function that converts between signatures is an adapter too:

// The target is a one-method interface, so a lambda can adapt the vendor call
WeatherSource source = city -> {
    LatLon p = cities.lookup(city).orElseThrow();
    return (api.fetch(p.lat(), p.lon()) - 32) * 5 / 9;
};

// Adapters in the JDK
Reader r = new InputStreamReader(System.in, StandardCharsets.UTF_8); // bytes -> chars
List<String> list = Arrays.asList(array);                           // array -> List view
Enumeration<String> e = Collections.enumeration(list);              // List -> legacy Enumeration

In Python, duck typing means you sometimes don't need an adapter at all: if the vendor object already has a method with the right name and meaning, it simply works. You need one when names, arguments, units or error types differ.

Adapters you already use

  1. Adapters are everywhere: wrapping old legacy code so new code can use it, plugging in third-party SDKs, or turning a stream of bytes into a stream of text, which is exactly what Java’s InputStreamReader does.

Other real examples: SLF4J's bridge modules (such as jcl-over-slf4j) adapt old logging APIs onto SLF4J; Spring MVC's HandlerAdapter lets one dispatcher call controllers of very different shapes; and in domain-driven design an anti-corruption layer is a set of adapters that keeps a legacy system's model from leaking into a new one.

Adapter, Decorator, Proxy, Facade: how they differ

All four wrap something, so they look alike on a class diagram. The difference is in the interfaces and the intent.

AdapterDecoratorProxyFacade
Interface it offersA different one (the target)The same as the wrapped objectThe same as the real objectA new, simpler one
WrapsOne objectOne object (often a chain)One objectA whole subsystem of many objects
IntentMake it fitAdd behaviourControl accessMake it easy to use
ExampleInputStreamReader (bytes to chars)BufferedReader (adds buffering)A lazy-loading imageOrderService.placeOrder()

A quick test: if the interface changes, it's an adapter. If it stays the same and something is added, decorator. If it stays the same and something is guarded or deferred, proxy. If many objects hide behind one simple front, facade.

When not to use it

In the interview

Your turn: two payment providers

Your checkout uses PaymentGateway.charge(String orderId, BigDecimal amount, String currency) and expects a PaymentResult (success or declined, plus a reference). Provider A's SDK takes the amount in minor units (long cents) and throws CardDeclinedException. Provider B takes a decimal string like "19.99" and returns a status code: 0 success, 51 insufficient funds, -1 network error. Sketch the two adapters.

Compare with our answer
class ProviderAAdapter implements PaymentGateway {
    private final ProviderAClient client;
    ProviderAAdapter(ProviderAClient client) { this.client = client; }
    public PaymentResult charge(String orderId, BigDecimal amount, String currency) {
        long minor = amount.movePointRight(2).longValueExact();   // 19.99 -> 1999 (2-decimal currencies)
        try {
            String ref = client.pay(orderId, minor, currency);
            return PaymentResult.ok(ref);
        } catch (CardDeclinedException e) {
            return PaymentResult.declined(e.getReason());
        }
    }
}

class ProviderBAdapter implements PaymentGateway {
    private final ProviderBClient client;
    ProviderBAdapter(ProviderBClient client) { this.client = client; }
    public PaymentResult charge(String orderId, BigDecimal amount, String currency) {
        BResponse r = client.submit(orderId, amount.toPlainString(), currency);
        return switch (r.code()) {
            case 0  -> PaymentResult.ok(r.reference());
            case 51 -> PaymentResult.declined("insufficient funds");
            default -> throw new PaymentUnavailableException("provider B code " + r.code());
        };
    }
}
class ProviderAAdapter(PaymentGateway):
    def __init__(self, client: ProviderAClient):
        self._client = client

    def charge(self, order_id: str, amount: Decimal, currency: str) -> PaymentResult:
        minor = int(amount * 100)                 # 2-decimal currencies only
        try:
            return PaymentResult.ok(self._client.pay(order_id, minor, currency))
        except CardDeclined as e:
            return PaymentResult.declined(e.reason)

class ProviderBAdapter(PaymentGateway):
    def __init__(self, client: ProviderBClient):
        self._client = client

    def charge(self, order_id: str, amount: Decimal, currency: str) -> PaymentResult:
        r = self._client.submit(order_id, str(amount), currency)
        if r.code == 0:
            return PaymentResult.ok(r.reference)
        if r.code == 51:
            return PaymentResult.declined("insufficient funds")
        raise PaymentUnavailable(f"provider B code {r.code}")

A strong answer mentions: both adapters implement the same PaymentGateway · amount conversion with exact decimals, not double · currencies with 0 or 3 decimal places (yen, dinar) need a per-currency exponent · a declined card is a normal result, while a network error is an exception the caller may retry · the order id passed through so retries can be deduplicated.

Your turn: the requirement changes

Provider B now limits you to 10 requests per second and charges per call, and the weather team wants the same for NewWeatherCo: "don't call them for the same city more than once every 10 minutes." Where does this logic go: in the adapter, in the app, or somewhere else?

Compare with our answer

A strong answer mentions: not in the app's screens, which should stay unaware of vendors · not mixed into the adapter's translation code, which should stay a pure translator · a separate wrapper with the same WeatherSource interface around the adapter (a caching proxy or decorator), so it works for any vendor · a time-to-live of 10 minutes keyed by city · a rate limiter or queue in front of provider B, plus what to show users when the limit is hit.

Adapter on one page
  • Intent: let a class with an incompatible interface work where your interface is expected, without changing either side.
  • Roles: target (your interface) · client · adaptee (theirs) · adapter (implements target, wraps adaptee).
  • Translate three things: inputs, outputs, errors.
  • Prefer object adapters (composition) over class adapters (inheritance), which leak the adaptee's API.
  • One-method targets: a lambda or plain function is an adapter.
  • Real ones: InputStreamReader, Arrays.asList, io.TextIOWrapper, functools.cmp_to_key, logging bridges, anti-corruption layers.
  • Not Decorator/Proxy (same interface) and not Facade (new simple front for many objects).
  • Watch for semantic gaps, hidden network calls and leaked vendor exceptions.
Interactive labPractise it: plug a new weather provider into the appOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Your app depends on SmsSender.send(phone, text). The new SMS vendor's SDK offers dispatch(Message m) and returns error codes instead of throwing. What is the cleanest way to adopt it?

2. Java's InputStreamReader takes an InputStream and is itself a Reader. Which pattern is it, and why?

3. A team's adapter translates method names and units, but vendor exceptions such as AcmeTimeoutException still reach the checkout code. What is the main risk?

4. When is a class adapter (inheriting from the adaptee) a reasonable choice over an object adapter?

5. A geocoding call inside your weather adapter adds 150 ms to every getTempC. The screens can't see it. What is the best fix?

6. Which description fits an adapter rather than a facade?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.