Cheatsheet

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.

Structure (UML)

Spring contextPulseBandMonitorPulseBandClient«i»HeartRateMonitorZoneControllerZoneBoardCoachHeartLinkMonitorHeartLinkHub

Participants

  • Target (HeartRateMonitor), the interface the client needs, in its own terms
  • Adaptee (PulseBandClient, HeartLinkHub), the existing class with a different interface, which you can't change
  • Adapter (PulseBandMonitor, HeartLinkMonitor), which implements the Target and translates every call to the Adaptee it wraps
  • Client (ZoneBoard), which only knows the Target

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);
}

Pros

  • The vendor's code doesn't leak into your domain, with its types, units and errors
  • Switching vendor means writing another adapter, not rewriting the client
  • Each translation lives in a small class that's easy to test

Cons

  • One more layer to read, and one class per thing you adapt
  • If the interface you design copies the vendor's, you've only renamed things
  • Some differences don't translate well (an SDK with no timestamp, say) and you have to decide what to do

← Adapter · Run it