LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 27 OF 48

Adapter Design Pattern in Java: Object and Class Adapters

The Adapter pattern explained with a fitness app that must read a third-party heart-rate band: the target, adaptee and adapter roles, translating units and errors, object adapter vs class adapter, wrapping a vendor SDK behind your own interface, when not to bother, Adapter vs Decorator, Proxy and Facade, and where it appears in Java and LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 179 lines, with a small main() demo. Save it as HeartRateAdapterDemo.java, then run javac HeartRateAdapterDemo.java && java HeartRateAdapterDemo.

// Adapter pattern: a fitness app reads a third-party heart-rate band through its own interface.
import java.util.List;

public class HeartRateAdapterDemo {

    public static void main(String[] args) {
        System.out.println("-- Before: the tracker knows every vendor --");
        NaiveWorkoutTracker naive = new NaiveWorkoutTracker();
        naive.logChest(new ChestStrap(142));
        naive.logBand(new PulseBandSdk(new int[] {400}));

        System.out.println("-- After: one interface, adapters at the edge --");
        PulseBandSdk band = new PulseBandSdk(new int[] {400, 410, 420});
        List<HeartRateMonitor> monitors = List.of(
                new ChestStrap(142),
                new PulseBandAdapter(band),                          // object adapter
                new PulseBandClassAdapter(new int[] {500}),          // class adapter
                new PulseBandAdapter(new PulseBandSdk(new int[] {-1})), // loose band
                new FakeHeartRate(175));                             // test double
        WorkoutTracker tracker = new WorkoutTracker();
        for (HeartRateMonitor monitor : monitors) {
            tracker.record(monitor);
        }
    }
}

// ---------------------------------------------------------------------------
// The problem: the tracker grows one method per brand and does vendor maths.
// ---------------------------------------------------------------------------
class NaiveWorkoutTracker {
    void logChest(ChestStrap strap) {
        System.out.println("chest strap: " + strap.beatsPerMinute() + " bpm");
    }

    void logBand(PulseBandSdk band) {
        int ms = band.lastBeatIntervalMs();          // vendor units leak into our code
        System.out.println("pulse band: " + (60_000 / ms) + " bpm"); // -1 gives nonsense
    }
}

// ---------------------------------------------------------------------------
// Target: the interface our code was designed around.
// ---------------------------------------------------------------------------
interface HeartRateMonitor {
    int beatsPerMinute();

    String source();
}

/** Already fits the target, so it needs no adapter. */
class ChestStrap implements HeartRateMonitor {
    private final int bpm;

    ChestStrap(int bpm) {
        this.bpm = bpm;
    }

    @Override
    public int beatsPerMinute() {
        return bpm;
    }

    @Override
    public String source() {
        return "chest strap";
    }
}

// ---------------------------------------------------------------------------
// Adaptee: pretend this class ships in a vendor jar we cannot edit.
// ---------------------------------------------------------------------------
class PulseBandSdk {
    private final int[] intervalsMs;
    private int cursor;

    PulseBandSdk(int[] intervalsMs) {
        this.intervalsMs = intervalsMs.clone();
    }

    /** Milliseconds between the last two beats, or -1 when the band is loose. */
    public int lastBeatIntervalMs() {
        int value = intervalsMs[cursor % intervalsMs.length];
        cursor++;
        return value;
    }

    public String serialNumber() {
        return "PB-0077";
    }
}

// ---------------------------------------------------------------------------
// Object adapter: implements the target, HOLDS the adaptee (composition).
// ---------------------------------------------------------------------------
class PulseBandAdapter implements HeartRateMonitor {
    private final PulseBandSdk band;

    PulseBandAdapter(PulseBandSdk band) {
        this.band = band;
    }

    @Override
    public int beatsPerMinute() {
        return toBpm(band.lastBeatIntervalMs());
    }

    @Override
    public String source() {
        return "pulse band " + band.serialNumber();   // translate naming
    }

    /** Shared translation: units (ms to bpm) and error style (-1 to exception). */
    static int toBpm(int intervalMs) {
        if (intervalMs <= 0) {
            throw new IllegalStateException("band is loose");
        }
        return 60_000 / intervalMs;
    }
}

// ---------------------------------------------------------------------------
// Class adapter: EXTENDS the adaptee and implements the target (inheritance).
// Only possible because PulseBandSdk is not final.
// ---------------------------------------------------------------------------
class PulseBandClassAdapter extends PulseBandSdk implements HeartRateMonitor {
    PulseBandClassAdapter(int[] intervalsMs) {
        super(intervalsMs);
    }

    @Override
    public int beatsPerMinute() {
        return PulseBandAdapter.toBpm(lastBeatIntervalMs());
    }

    @Override
    public String source() {
        return "pulse band (class adapter) " + serialNumber();
    }
}

/** A fake for tests: no hardware, no vendor jar. */
class FakeHeartRate implements HeartRateMonitor {
    private final int bpm;

    FakeHeartRate(int bpm) {
        this.bpm = bpm;
    }

    @Override
    public int beatsPerMinute() {
        return bpm;
    }

    @Override
    public String source() {
        return "fake";
    }
}

// ---------------------------------------------------------------------------
// Client: depends only on the target interface.
// ---------------------------------------------------------------------------
class WorkoutTracker {
    void record(HeartRateMonitor monitor) {
        try {
            int bpm = monitor.beatsPerMinute();
            System.out.println(monitor.source() + ": " + bpm + " bpm, zone " + zoneFor(bpm));
        } catch (IllegalStateException e) {
            System.out.println(monitor.source() + ": no reading (" + e.getMessage() + ")");
        }
    }

    private static String zoneFor(int bpm) {
        if (bpm >= 160) {
            return "hard";
        }
        return bpm >= 120 ? "moderate" : "easy";
    }
}

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.

NaiveWorkoutTracker
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.

Adapter in one line
  • 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.

What we have
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.

PulseBandAdapter
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.

What an adapter translates
  • 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.

PulseBandClassAdapter
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.

Which one?
  • 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.

Why wrap a vendor SDK
  • 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 / avoid
  • 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.

Adapters in Java
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.

Wrappers compared
  • 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.

Where it shows up
  • 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.

In the interview
  • "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."

Interview questions

What problem does the Adapter pattern solve?

It lets a class with an incompatible interface work with code that expects a different interface, without changing either side. A small adapter class implements the expected interface and translates each call to the existing class.

What is the difference between an object adapter and a class adapter?

An object adapter holds a reference to the adaptee and delegates to it (composition). A class adapter extends the adaptee and implements the target (inheritance). In Java the object adapter is usually preferred because it works with final classes, can wrap any subclass or mock, and does not expose the adaptee's other public methods.

How is Adapter different from Decorator?

An adapter changes the interface the client sees and keeps the behaviour. A decorator keeps exactly the same interface and adds behaviour, and decorators can be stacked. If the wrapper implements the same interface as the wrapped object, it is not an adapter.

How is Adapter different from Facade?

An adapter makes one existing class match one interface that already exists. A facade defines a new, simpler interface over a whole subsystem of many classes to make it easier to use. Adapter is about compatibility; facade is about simplicity.

Why wrap a third-party SDK behind your own interface?

It keeps vendor types out of business code, lets you switch or add providers by writing one new adapter, makes testing easy with a fake implementation, and limits the damage of a breaking vendor upgrade to one class.

Give examples of the Adapter pattern in the Java standard library.

Arrays.asList presents an array as a fixed-size List backed by that array. InputStreamReader adapts a byte InputStream into a character Reader. Collections.enumeration adapts a Collection to the legacy Enumeration interface, and Collections.list converts an Enumeration back into an ArrayList.

Should an adapter contain business logic?

No. It should only translate: names, units, data shapes and error styles. Business rules inside an adapter get duplicated when you add a second provider and are hidden in a place nobody expects, so keep adapters thin.

Where would you use Adapter in an LLD interview problem?

Wherever the design touches external systems: payment providers in parking lot or booking systems, SMS and email vendors in a notification service, or third-party storage and log sinks. Define your own interface first, then one adapter per vendor.