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.
On this page
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
- 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.
- 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
- 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.
| Role | In this example | Responsibility |
|---|---|---|
| Target | WeatherSource | The interface the client code is written against |
| Client | WeatherScreen | Uses only the target |
| Adaptee | NewWeatherCo | The existing class with the incompatible interface |
| Adapter | NewWeatherAdapter | Implements 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());
}
}
}from abc import ABC, abstractmethod
# --- Our side: the target interface and a client ---
class WeatherUnavailable(Exception):
pass
class WeatherSource(ABC):
@abstractmethod
def get_temp_c(self, city: str) -> float: ...
class WeatherScreen: # the client: knows only WeatherSource
def __init__(self, source: WeatherSource):
self.source = source
def headline(self, city: str) -> str:
return f"{city}: {self.source.get_temp_c(city):.1f} °C"
# --- Their side: a library we cannot change (the adaptee) ---
class NewWeatherCo:
def fetch(self, lat: float, lon: float) -> float: # Fahrenheit
return 71.6
CITIES = {"Lisbon": (38.72, -9.14)}
# --- The adapter ---
class NewWeatherAdapter(WeatherSource):
def __init__(self, api: NewWeatherCo, cities: dict[str, tuple[float, float]]):
self._api = api
self._cities = cities
def get_temp_c(self, city: str) -> float:
if city not in self._cities: # translate the input
raise WeatherUnavailable(f"Unknown city: {city}")
lat, lon = self._cities[city]
try:
f = self._api.fetch(lat, lon)
except (ValueError, ConnectionError) as e: # translate their errors
raise WeatherUnavailable(f"Provider failed for {city}") from e
return (f - 32) * 5 / 9 # translate the output
screen = WeatherScreen(NewWeatherAdapter(NewWeatherCo(), CITIES))
print(screen.headline("Lisbon")) # Lisbon: 22.0 °C
try:
screen.headline("Atlantis")
except WeatherUnavailable as e:
print("Shown to user:", e)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 with | Any adaptee, including final classes and interfaces | Only non-final classes |
| Exposes | Only the target's methods | The target's methods and every public adaptee method |
| Swap the adaptee at run time or in tests | Yes, pass a different object or a mock | No, it is fixed at compile time |
| Use when | Almost always | Rarely: 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 Enumerationimport functools, io
# A plain function adapts the vendor call to our signature
def temp_c(city: str) -> float:
lat, lon = CITIES[city]
return (api.fetch(lat, lon) - 32) * 5 / 9
# Adapters in the standard library
text = io.TextIOWrapper(binary_file, encoding="utf-8") # bytes -> text
def compare_len(a, b): return len(a) - len(b) # an old-style comparator...
sorted(words, key=functools.cmp_to_key(compare_len)) # ...adapted to a key functionIn 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
- 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.
| Adapter | Decorator | Proxy | Facade | |
|---|---|---|---|---|
| Interface it offers | A different one (the target) | The same as the wrapped object | The same as the real object | A new, simpler one |
| Wraps | One object | One object (often a chain) | One object | A whole subsystem of many objects |
| Intent | Make it fit | Add behaviour | Control access | Make it easy to use |
| Example | InputStreamReader (bytes to chars) | BufferedReader (adds buffering) | A lazy-loading image | OrderService.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 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.
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.
- 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.
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?
An object adapter keeps both sides unchanged and puts all translation, including errors, in one place. Subclassing works but exposes the vendor's whole API through the adapter.
2. Java's InputStreamReader takes an InputStream and is itself a Reader. Which pattern is it, and why?
The interface changes from InputStream (bytes) to Reader (chars), which is the defining mark of an adapter. BufferedReader, which wraps a Reader and is still a Reader, is the decorator.
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?
Error types are part of an interface. If they leak, switching vendors means editing callers again. Map vendor errors to your own exception types inside the adapter.
4. When is a class adapter (inheriting from the adaptee) a reasonable choice over an object adapter?
Only inheritance can override protected methods. Final classes cannot be subclassed at all, test doubles are easier with composition, and in Java a class adapter needs the target to be an interface.
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?
Coordinates for a city are stable, so caching them removes the repeated network call while keeping the translation in one place. Pushing the lookup into screens spreads vendor details through the app.
6. Which description fits an adapter rather than a facade?
An adapter converts one interface into another expected one. A facade simplifies a whole subsystem; the other two describe a decorator and a virtual proxy.
Score 60% or more and the lesson is marked complete.