Adapter
- Intent
- Put a translator between your code and a class you can't change, so your code only talks to the interface it designed and the translator turns each call into something that class understands.
- Application
- The box switches heart-rate bands and the new vendor speaks another language. Define the interface your app needs and write one adapter per vendor, without touching their SDK or your code.
The coach asks ZoneController for GET /api/zones/ana, which calls VendorBoundZoneBoard, highlighted in red; it calls PulseBandClient directly with latestBeat("PB-0042").
HeartLinkHub appears next to PulseBandClient. VendorBoundZoneBoard and HeartLinkHub, highlighted, don't fit: readSample(3) looks like nothing the board knows how to use.
The HeartRateMonitor interface appears, highlighted, and ZoneBoard asks it for current("ana").
PulseBandMonitor, highlighted, plugs into HeartRateMonitor. ZoneBoard asks for current("ana") and the adapter calls PulseBandClient with latestBeat("PB-0042").
The Spring context appears. ZoneBoard, highlighted together with the context, is wired to HeartRateMonitor, where PulseBandMonitor is plugged in, using PulseBandClient.
GET /api/zones/ana travels from the coach to the controller, zoneOf("ana") to ZoneBoard, current() to the interface, and PulseBandMonitor, highlighted with ZoneBoard, reads 2.6 beats/s from PulseBandClient.
HeartLinkMonitor, highlighted, plugs into HeartRateMonitor next to PulseBandMonitor and reads from HeartLinkHub with readSample(3).
With the heartlink property, the Spring context has HeartLinkMonitor, highlighted, plugged in instead of PulseBandMonitor. GET /api/zones/ana arrives the same way and the adapter reads "HR=171;T=…" from HeartLinkHub.
Inside the Spring context, DispatcherServlet calls handle() on the HandlerAdapter interface, highlighted, where RequestMappingHandlerAdapter and HttpRequestHandlerAdapter are plugged in; the latter, highlighted, calls handleRequest() on /legacy/ping.
Final view: the coach, the controller, ZoneBoard and HeartRateMonitor with both adapters plugged in, each with its SDK, all inside the Spring context.
Step 1 of 10
The zones board
During class, the box's screen shows which heart-rate zone each athlete is in (1 to 5, by percentage of their max heart rate). Ana wears a PulseBand band and the app uses the vendor's SDK, PulseBandClient.
The first version, VendorBoundZoneBoard, calls the SDK directly: it looks up the band's serial number, calls latestBeat(...), turns beats per second into beats per minute and milliseconds into an Instant.
Step 2 of 10
The new straps arrive
The box switches to HeartLink straps, read from a hub on the wall. Its SDK looks nothing alike:
- Straps are identified by radio channel, not serial number.
readSample(3)returns text:"HR=171;T=1700000000", with the time in seconds.- With no signal it doesn't throw, it returns
"NO_SIGNAL".
Every highlighted line depends on PulseBand. You'd have to rewrite the board, and do it again with the next vendor.
Step 3 of 10
First, what you need
Adapter starts on your side: define the interface the board needs, in its own terms. That's HeartRateMonitor:
- it takes the athlete's id, not a serial number or a channel;
- it returns a
HeartRatein beats per minute, with itsInstant; - with no signal, it returns
Optional.empty().
No vendor type shows up anywhere. It's the pattern's Target.
Step 4 of 10
One adapter per vendor
PulseBandMonitor implements HeartRateMonitor and wraps a PulseBandClient. Every call is translated:
- the athlete's id becomes a serial number;
- beats per second become beats per minute, and milliseconds an
Instant; - the vendor's
PulseBandExceptionbecomes "no signal".
The SDK doesn't change and neither does the board. All the translation lives in this class.
Step 5 of 10
The board no longer knows about vendors
In Spring, ZoneBoard gets a HeartRateMonitor through its constructor. It asks for the heart rate, works out the zone with the athlete's max heart rate, and that's it.
It imports nothing from vendor.pulseband or vendor.heartlink. The SDK and its adapter are declared as beans in a separate @Configuration class which, apart from the adapter itself, is the only place where the vendor's name appears.
Step 6 of 10
Ana, in zone 4
Ana's band reads 2.6 beats per second:
GET /api/zones/anareachesZoneController, which callsZoneBoard.ZoneBoardasks itsHeartRateMonitorforcurrent("ana").PulseBandMonitortranslates: serialPB-0042, 2.6 × 60 = 156 bpm.- With a max of 190, that's 82%: zone 4.
Step 7 of 10
The second adapter
For HeartLink you write HeartLinkMonitor, another adapter for the same Target:
- it looks up the athlete's channel and calls
readSample(channel); - if it gets
"NO_SIGNAL", it returns empty; - otherwise it parses
"HR=171;T=1700000000"and turns the seconds into anInstant.
And if the text can't be read, it doesn't make up a heart rate: it throws MonitorException. The API answers 502, because the fault is the device's and not the caller's, with a neutral message; the vendor details go to the log.
Step 8 of 10
Switching vendor is configuration
Each vendor has its own @Configuration with @ConditionalOnProperty:
PulseBandConfigis active when nothing is set (matchIfMissing = true).HeartLinkConfig, withbox.monitors.vendor=heartlink.
You change one line in application.properties, Spring registers the other SDK and the other adapter, and ZoneBoard gets a different HeartRateMonitor without noticing. The HeartLinkWiringTest test checks it. And if someone misspells the vendor's name, no adapter is activated and the app fails at startup, not at the first reading.
Step 9 of 10
Spring already does it for you
The DispatcherServlet serves very different handlers: @GetMapping methods on a @RestController, an old-style HttpRequestHandler, router functions (RouterFunction)… It can't call any of them directly. For each handler it looks for the HandlerAdapter that answers true to supports(handler) and asks it to handle(...):
RequestMappingHandlerAdapterfor@RequestMappingmethods (and@GetMapping,@PostMapping…);HttpRequestHandlerAdapterfor anHttpRequestHandler;- and others, such as
SimpleControllerHandlerAdapterorHandlerFunctionAdapter.
The example test registers an HttpRequestHandler with the bean name "/legacy/ping". BeanNameUrlHandlerMapping, which Spring MVC registers by default, maps beans whose name starts with / to a URL. Then it calls it alongside the zones API, and the same servlet serves both.
Step 10 of 10
Recap
You started with a board tied to one vendor and ended up with:
- A Target,
HeartRateMonitor, in the box's language. - One adapter per vendor, wrapping its SDK and translating ids, units and errors.
- A client,
ZoneBoard, that doesn't know which band anyone wears. - The vendor choice in the configuration.
Don't mix it up with its neighbours: Decorator keeps the interface and adds behaviour; Proxy keeps the interface and controls access to the object; Facade offers a simpler interface to a whole subsystem; Adapter turns one interface into another that already exists.
And when you don't need it: if you own both sides, change the interface directly; if the external type already fits what you need, use it as is; and if you only call it from one place, a function that converts the result is sometimes enough.
Code
VendorBoundZoneBoard.java
public Optional<ZoneReading> zoneOf(String athleteId) {
Athlete a = roster.find(athleteId).orElseThrow(() -> new NoSuchElementException("unknown athlete"));
String serial = SERIALS.get(a.id());
if (serial == null) return Optional.empty();
PulseBandBeat beat;
try {
beat = pulseBand.latestBeat(serial);
} catch (PulseBandException e) {
return Optional.empty();
}
int bpm = (int) Math.round(beat.beatsPerSecond() * 60); // PulseBand counts per second
Instant at = Instant.ofEpochMilli(beat.epochMillis());
return Optional.of(new ZoneReading(a.name(), bpm, Zone.of(bpm, a.maxHr()), at));
}VendorBoundZoneBoard.java
public Optional<ZoneReading> zoneOf(String athleteId) {
Athlete a = roster.find(athleteId).orElseThrow(() -> new NoSuchElementException("unknown athlete"));
String serial = SERIALS.get(a.id());
if (serial == null) return Optional.empty();
PulseBandBeat beat;
try {
beat = pulseBand.latestBeat(serial);
} catch (PulseBandException e) {
return Optional.empty();
}
int bpm = (int) Math.round(beat.beatsPerSecond() * 60); // PulseBand counts per second
Instant at = Instant.ofEpochMilli(beat.epochMillis());
return Optional.of(new ZoneReading(a.name(), bpm, Zone.of(bpm, a.maxHr()), at));
}HeartRateMonitor.java
/** The target: what the box needs from any heart-rate band, in its own words. */
public interface HeartRateMonitor {
/** The athlete's latest heart rate, or empty if their band has no signal. */
Optional<HeartRate> current(String athleteId);
}PulseBandMonitor.java
@Override
public Optional<HeartRate> current(String athleteId) {
String serial = serialByAthlete.get(athleteId); // our id → their serial
if (serial == null) return Optional.empty();
try {
PulseBandBeat beat = band.latestBeat(serial);
long bpm = Math.round(beat.beatsPerSecond() * 60); // per second → per minute
if (bpm < 20 || bpm > 250) {
throw new MonitorException("implausible PulseBand reading: " + bpm + " bpm");
}
return Optional.of(new HeartRate((int) bpm, Instant.ofEpochMilli(beat.epochMillis())));
} catch (PulseBandException e) {
return Optional.empty(); // their error → our "no signal"
}
}ZoneBoard.java
public Optional<ZoneReading> zoneOf(String athleteId) {
Athlete a = roster.find(athleteId)
.orElseThrow(() -> new UnknownAthleteException(abbreviate(athleteId)));
return monitor.current(a.id())
.map(hr -> new ZoneReading(a.name(), hr.bpm(), Zone.of(hr.bpm(), a.maxHr()), hr.at()));
}ZoneBoardTest.java
band.simulate("PB-0042", 2.6, 1_700_000_000_000L); // 156 bpm
ZoneReading ana = board.zoneOf("ana").orElseThrow();
assertThat(ana.bpm()).isEqualTo(156);
assertThat(ana.zone()).isEqualTo(4); // 82% of her max (190)HeartLinkMonitor.java
@Override
public Optional<HeartRate> current(String athleteId) {
Integer channel = channelByAthlete.get(athleteId);
if (channel == null) return Optional.empty();
String raw = hub.readSample(channel); // "HR=171;T=1700000000"
if (HeartLinkHub.NO_SIGNAL.equals(raw)) return Optional.empty();
Matcher m = SAMPLE.matcher(raw);
if (!m.matches()) throw new MonitorException("unreadable HeartLink sample on channel " + channel);
int bpm = Integer.parseInt(m.group(1));
if (!HeartRate.plausible(bpm)) {
throw new MonitorException("implausible HeartLink reading: " + bpm + " bpm");
}
return Optional.of(new HeartRate(bpm, Instant.ofEpochSecond(Long.parseLong(m.group(2)))));
}HeartLinkConfig.java
/** The new straps: switch with box.monitors.vendor=heartlink. ZoneBoard doesn't change. */
@Configuration
@ConditionalOnProperty(name = "box.monitors.vendor", havingValue = "heartlink")
class HeartLinkConfig {
@Bean
HeartLinkHub heartLinkHub() {
return new HeartLinkHub();
}
@Bean
HeartRateMonitor heartLinkMonitor(HeartLinkHub hub) {
return new HeartLinkMonitor(hub, Map.of("ana", 3));
}
}SpringDoesItTooTest.java
@TestConfiguration
static class OldSchool {
@Bean("/legacy/ping") // not a @RestController: a plain HttpRequestHandler, mapped by bean name
HttpRequestHandler legacyPing() {
return (request, response) -> response.getWriter().write("pong");
}
}
@Autowired MockMvc mvc;
@Autowired List<HandlerAdapter> adapters;
@Test void oneDispatcherServletManyKindsOfHandler() throws Exception {
mvc.perform(get("/legacy/ping")).andExpect(content().string("pong")); // HttpRequestHandlerAdapter
mvc.perform(get("/api/zones/leo")).andExpect(status().isNoContent()); // RequestMappingHandlerAdapter
assertThat(adapters).hasAtLeastOneElementOfType(RequestMappingHandlerAdapter.class)
.hasAtLeastOneElementOfType(HttpRequestHandlerAdapter.class);
}HeartRateMonitor.java
/** The target: what the box needs from any heart-rate band, in its own words. */
public interface HeartRateMonitor {
/** The athlete's latest heart rate, or empty if their band has no signal. */
Optional<HeartRate> current(String athleteId);
}