Notes
The problem
Our fitness app has a workout tracker that reads a chest strap in beats per minute. Now we must support a wrist band from another company. Its SDK reports the time between two beats in milliseconds, and minus one when the band is loose. The naive tracker grows a new method per brand, does the unit maths itself, and breaks on that minus one. Every new device means editing the tracker again.
void logChest(ChestStrap s) {
print(s.beatsPerMinute() + " bpm");
}
void logBand(PulseBandSdk b) {
int ms = b.lastBeatIntervalMs();
print(60_000 / ms + " bpm");
}
one method per device brand
vendor units inside our logic
ms of -1 crashes the maths The idea
The idea in one sentence. Write one small class that implements the interface your code expects, and inside, calls the class that does not fit. That class is the adapter. More formally, an adapter converts the interface of a class into another interface that clients expect, so classes that could not work together now can. Think of a travel plug adapter. Neither the wall socket nor your charger changes.
- keep the interface you have
- write one small class that
- implements it and calls the
- class you cannot change
- it translates names, units,
- data shapes and errors
- like a travel plug adapter:
- neither the wall nor the
- charger changes
The roles
Four roles. The client is the workout tracker. The target is the heart rate monitor interface it already depends on. The adaptee is the pulse band SDK class, shipped in a vendor jar we cannot edit. The adapter is the pulse band adapter, which implements the target and holds an adaptee. The chest strap already fits, so it implements the interface directly and needs no adapter at all.
Target and adaptee
Here are the two shapes. Our target interface is tiny: beats per minute, and a source name for display. The vendor class speaks a different language. It gives the interval between the last two beats in milliseconds, returns minus one when the band is loose, and names itself by serial number. Nothing here is wrong. The two sides were simply designed by different people for different needs.
interface HeartRateMonitor {
int beatsPerMinute();
String source();
}
// vendor jar, read only
class PulseBandSdk {
int lastBeatIntervalMs(); // -1 = loose
String serialNumber();
} Object adapter
The adapter takes the vendor object in its constructor and keeps it in a final field. When the tracker asks for beats per minute, the adapter asks the band for its interval, checks for the loose band signal and turns it into an exception our code already handles, then divides sixty thousand by the interval. Four hundred milliseconds between beats becomes one hundred and fifty beats per minute.
class PulseBandAdapter
implements HeartRateMonitor {
private final PulseBandSdk band;
public int beatsPerMinute() {
int ms = band.lastBeatIntervalMs();
if (ms <= 0) throw new
IllegalStateException("loose");
return 60_000 / ms;
}
} More than renaming
An adapter often does more than rename methods. It converts units, like milliseconds to beats per minute. It converts error styles, like a magic minus one into a proper exception. It maps vendor data objects into your own records, and can even turn callbacks into return values. What it should not do is hold business rules. Keep it thin, so the only reason it changes is that the vendor changed.
- names: serialNumber to source
- units: ms between beats to bpm
- errors: -1 to an exception
- our code already catches
- types: vendor DTOs to records
- shape: callbacks to return
- values, or the reverse
- it should NOT add business
- rules: keep it thin
One call
Follow one call. The tracker holds what it thinks is just a heart rate monitor and asks for beats per minute. The adapter forwards the request to the vendor band as last beat interval. The band answers four hundred. The adapter converts that and returns one hundred and fifty. The tracker picks the heart rate zone exactly as it does for the chest strap. It has no idea a vendor class was involved.
Class adapter
There is a second form, the class adapter. Instead of holding a band object, it extends the vendor class and implements our interface. It calls the inherited method directly. Java has single class inheritance, so this only works when the adaptee is a class that is not final, and the adapter can extend just one adaptee. Languages with multiple inheritance use this form more often.
class PulseBandClassAdapter
extends PulseBandSdk
implements HeartRateMonitor {
public int beatsPerMinute() {
int ms = lastBeatIntervalMs();
...same translation...
}
}
only works if the class is not final Object vs class
Which form should you pick? Usually the object adapter. It works with final classes, it can wrap an object that already exists, including a subclass or a test mock, and it exposes only the target methods. The class adapter can override some adaptee behaviour, but it ties you to one concrete vendor class, and every public vendor method leaks through the adapter. In interviews, say you prefer composition here.
- object adapter (has-a):
- + works with final classes
- + wraps any subclass or mock
- + can wrap an existing object
- - one extra object
- class adapter (is-a):
- + can override adaptee methods
- - adaptee must be extendable
- - leaks all vendor methods
- - one adaptee only
Wrapping an SDK
This is why teams wrap every third party SDK, even when it seems to fit. Vendor types stay inside one package behind your own interface. Switching vendors means writing one new adapter, with no change to business code. Tests use a simple fake monitor instead of real hardware. A breaking vendor upgrade touches one class. Design the interface around what your code needs, not as a copy of the vendor's API.
- vendor types stay in one
- package, behind your interface
- switch vendors: new adapter,
- zero business code changes
- tests use a fake, no device
- vendor upgrade breaks one
- class, not fifty
- design the interface for your
- needs, not as a copy of theirs
When to use it
Use an adapter at boundaries: when a class you cannot change has to fit your interface, when legacy code meets new code, and around any third party SDK for payments, messages, maps or storage. Skip it when you own both sides. Then just change one of them instead of adding a translator. And if an adapter starts collecting business rules, that logic belongs somewhere else.
- use when:
- • a class you cannot change
- must fit your interface
- • legacy code meets new code
- • third-party payment, SMS,
- maps or storage SDKs
- avoid when:
- • you own both sides: just
- change the interface
- • it starts holding logic
In the JDK
The Java standard library has several. Arrays dot as list lets an array be used through the List interface, backed by the same array, which is why its size is fixed. Input stream reader turns a byte stream into a character reader, decoding with a charset. Collections dot enumeration presents a collection through the old enumeration interface that legacy APIs expect, and collections dot list goes back the other way.
Arrays.asList(array) // array seen as a fixed-size List new InputStreamReader(in, UTF_8) // byte stream seen as a Reader Collections.enumeration(list) // Collection seen as old Enumeration Collections.list(enumeration) // and back to an ArrayList
Neighbours
Four patterns wrap other objects, so people mix them up. Ask what happens to the interface. An adapter changes it: the client sees a different interface than the wrapped class has, and behaviour stays the same. A decorator keeps the same interface and adds behaviour, and you can stack several. A proxy keeps the same interface and controls access. A facade puts one new, simpler interface over a whole group of classes.
- Adapter: DIFFERENT interface,
- same behaviour (translate)
- Decorator: SAME interface,
- extra behaviour (stackable)
- Proxy: SAME interface,
- controls access (lazy, auth,
- remote, cache)
- Facade: NEW simpler interface
- over a whole subsystem
In LLD interviews
In machine coding rounds, adapter shows up at every external edge. Parking lot and movie booking designs use a payment gateway interface with one adapter per provider. A notification service adapts each SMS and email vendor. A logger adapts third party sinks. Common mistakes: letting vendor types leak into the client, putting business logic in the adapter, and calling something an adapter when it keeps the same interface.
- parking lot, movie booking:
- PaymentGateway interface,
- one adapter per provider
- notification service:
- SMS and email vendors
- logger: third-party sinks
- mistakes:
- • vendor types in the client
- • logic inside the adapter
- • calling a wrapper "adapter"
- when the interface is same
Say it like this
How to say it. Checkout depends only on our payment gateway interface. Each provider SDK gets an object adapter that maps our request into theirs and their error codes into our exceptions. Switching or adding a provider is one new class, and tests use a fake gateway. That one sentence shows you know the roles, prefer composition, and use adapters to protect the core from outside change.
- "Checkout depends on our
- PaymentGateway interface.
- Each provider SDK gets an
- object adapter that maps our
- request to theirs and their
- errors to ours. Switching
- providers is one new class,
- and tests use a fake."