Adapter

November 25, 20268 minutes

Twelve call sites print receipts, and the new printer only speaks bytes. Learn how one Adapter class lets your code keep its own interface, and how it differs from Decorator, Proxy and Facade.

Your café app prints receipts from twelve places. Checkout, refunds, the kitchen ticket, the end of day report. Every one of them calls print, with a list of lines. Then the café buys a new printer. Its software doesn’t know what a line of text is. It wants bytes, and then a cut command. Do you change all twelve places, to talk to one printer? There’s a better way, and it’s called the Adapter pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

Twelve places, one printer

Changing the twelve call sites works today. But next year there’s another printer, and all twelve change again. When every caller speaks the vendor’s language, every vendor change is a change everywhere.

Twelve call sites (checkout, refunds, kitchen ticket, end of day and eight more) all call the ThermoJet printer's feed and cut methods directly; next year's printer would mean changing all twelve again. Twelve call sites (checkout, refunds, kitchen ticket, end of day and eight more) all call the ThermoJet printer's feed and cut methods directly; next year's printer would mean changing all twelve again.
Every caller speaks the printer's language.

A translator

Picture a meeting with a visitor who speaks another language. Nobody on your team learns it overnight. So you bring in a translator. You speak the way you always do. The translator listens, and says the same thing in the visitor’s language. She changes the words, not the meaning. And when next month’s visitor speaks something else, you bring a different translator. Your team stays exactly as it is.

In code, your team is the client, and the language it speaks is the target interface. The visitor is the adaptee. And the translator is the adapter.

The translator analogy mapped onto code: the team is the client (the checkout); the team's language is the target (ReceiptPrinter); the visitor is the adaptee (ThermoJet); the translator is the adapter (ThermoJetPrinter). The translator analogy mapped onto code: the team is the client (the checkout); the team's language is the target (ReceiptPrinter); the visitor is the adaptee (ThermoJet); the translator is the adapter (ThermoJetPrinter).
The meeting, mapped onto the code.

The obvious version: talk to the printer directly

Here’s the interface the app already uses. A receipt printer has one method, print, and it takes a list of lines.

public interface ReceiptPrinter {
    void print(List<String> lines);
}

And here’s the vendor’s class. feed takes bytes, and cut ends the receipt. You can’t edit it. It ships inside their library.

// the vendor's SDK: you can't edit it
public class ThermoJet {
    public void feed(byte[] data) { /* ... */ }
    public void cut() { /* ... */ }
}

The obvious move, at the checkout: join the lines, turn them into bytes, feed them in, and cut. Four lines, copied from the vendor’s sample.

byte[] data = String.join("\n", receipt.lines())
        .getBytes(StandardCharsets.US_ASCII);
jet.feed(data);
jet.cut();

For one call site, that’s fair. It’s direct, and you can read it in one go.

Why it breaks

But there are twelve call sites. So the same four lines get pasted twelve times, and every copy knows the vendor’s class.

Then a customer orders a crème brûlée, and the receipt prints question marks where the accents go: cr?me br?l?e. The sample code used US-ASCII, which has no accents, and String.getBytes replaces every character it can’t encode with the charset’s replacement byte, ?. The fix is one word, ISO_8859_1 (Latin-1). But it’s one word in twelve places, and the place you miss keeps printing question marks.

One accent fix (switch US_ASCII to ISO_8859_1) has to be made in each of the twelve pasted copies; the one that's missed keeps printing question marks. One accent fix (switch US_ASCII to ISO_8859_1) has to be made in each of the twelve pasted copies; the one that's missed keeps printing question marks.
One fix, twelve edits.

Testing the checkout now needs the real printer. And when the next vendor arrives, all twelve change again. It’s a whole team learning the visitor’s language, with one phrasebook each.

The key idea: translate in one place

The app and the printer agree on what to do: print this receipt. They only disagree on how to say it. So write one class that speaks both. It implements your ReceiptPrinter, and inside, it holds the vendor’s ThermoJet. Your twelve call sites keep calling print. Only the adapter knows the printer’s language.

The Gang of Four put it this way (Design Patterns, 1994):

“Convert the interface of a class into another interface clients expect.”

Change the shape, not the job.

Building it

Here’s the adapter. It implements ReceiptPrinter, and its constructor takes the ThermoJet it wraps. print does the translation: join the lines, encode them as Latin-1, feed in the bytes, and then cut.

public class ThermoJetPrinter implements ReceiptPrinter {
    private final ThermoJet jet;

    public ThermoJetPrinter(ThermoJet jet) { this.jet = jet; }

    @Override
    public void print(List<String> lines) {
        byte[] data = String.join("\n", lines)
                .getBytes(StandardCharsets.ISO_8859_1);
        jet.feed(data);
        jet.cut();
    }
}

Follow one receipt through. The checkout calls print with three lines. The adapter turns them into bytes, feeds the ThermoJet, and cuts. The checkout never finds out.

Sequence: Checkout calls print(lines) on ThermoJetPrinter; the adapter joins and encodes the lines, calls feed(bytes) and then cut() on ThermoJet. The checkout only ever sees print. Sequence: Checkout calls print(lines) on ThermoJetPrinter; the adapter joins and encodes the lines, calls feed(bytes) and then cut() on ThermoJet. The checkout only ever sees print.
Your interface outside, their class inside.

The app picks its printer in one line, when it starts up. The twelve call sites don’t change at all.

ReceiptPrinter printer = new ThermoJetPrinter(new ThermoJet());

And the accent fix from before? It lives in exactly one place now: the ISO_8859_1 line. Tests get easier too. A fake printer that records the lines can stand in, and no paper comes out.

class FakePrinter implements ReceiptPrinter {
    final List<String> printed = new ArrayList<>();

    @Override
    public void print(List<String> lines) { printed.addAll(lines); }
}

When a new printer arrives next year, it gets its own adapter class, and nothing else in the app moves.

Anatomy

The pattern has four roles. The checkout is the client. ReceiptPrinter is the target, the interface the client expects. ThermoJet is the adaptee. And the class in the middle is the adapter.

Class diagram of Adapter: Checkout (client) uses the ReceiptPrinter interface (target) with print(lines). ThermoJetPrinter (adapter) implements ReceiptPrinter and holds a ThermoJet (adaptee) with feed(bytes) and cut(). Class diagram of Adapter: Checkout (client) uses the ReceiptPrinter interface (target) with print(lines). ThermoJetPrinter (adapter) implements ReceiptPrinter and holds a ThermoJet (adaptee) with feed(bytes) and cut().
Four roles: an object adapter holds the adaptee.

This one holds the ThermoJet in a field. That’s an object adapter. Java also lets you write a class adapter, which extends the vendor’s class instead:

public class ThermoJetPrinter extends ThermoJet implements ReceiptPrinter {
    @Override
    public void print(List<String> lines) {
        feed(String.join("\n", lines).getBytes(StandardCharsets.ISO_8859_1));
        cut();
    }
}

It’s shorter, but it’s welded to that one class, and it hands every public vendor method (feed, cut) to your callers. The Gang of Four note the trade-off: a class adapter is tied to one concrete adaptee class, while an object adapter works with the adaptee and all its subclasses. Prefer holding over extending.

Adapters range from a simple rename to a real conversion (GoF: “Adapters vary in the amount of work they do”). Keep yours to what the app needs. If the app only prints, adapt printing, not everything the vendor offers. There’s also a two-way adapter, which speaks each side’s language to the other. You’ll rarely need one, but now you know the name.

In the JDK: Arrays.asList and Collections.enumeration

The JDK ships adapters too. Arrays.asList takes an array, and hands it back dressed as a list.

String[] specials = {"flat white", "chai", "mocha"};
List<String> menu = Arrays.asList(specials);
menu.set(0, "cortado");   // specials[0] is now "cortado"

It doesn’t copy anything. The list is a view over the same array (the javadoc: “Returns a fixed-size list backed by the specified array”). Set the first item through the list, and the array changes too. It translates the shape, and some things don’t fit. An array can’t grow, so adding to that list throws an UnsupportedOperationException.

It also runs the other way. Collections.enumeration wraps a modern collection for old code that still expects an Enumeration (the javadoc: “interoperability with legacy APIs that require an enumeration as input”).

Enumeration<String> legacy = Collections.enumeration(menu);

And the enumeration has a method called asIterator (Java 9+), which adapts it straight back. When a method’s name starts with as, there’s often an adapter behind it.

The mix-up: Decorator, Proxy and Facade

Now a common mix-up: any wrapper is an adapter. Decorators and proxies wrap things too. The difference is the interface.

  • A decorator keeps the same interface, and adds one more job, like logging (see Decorator: “Same interface, one more job”).
  • A proxy keeps it too, and guards the way in.
  • An adapter changes the interface, and keeps the job. A translator who adds his own opinions has stopped translating.
WrapperInterface in → outWhat it adds
DecoratorReceiptPrinter → ReceiptPrinterone more job
ProxyReceiptPrinter → ReceiptPrinterguards access
AdapterReceiptPrinter → ThermoJetnothing: same job

The other look-alike is the facade. A facade puts one new, simpler front on a whole group of classes. An adapter usually wraps one class, to fit an interface you already have. A translator makes one conversation work. A wedding planner turns five calls into one (that’s the analogy in the Facade lesson).

Side by side: an adapter wraps one class (ThermoJet) so it fits an interface you already have (ReceiptPrinter); a facade puts one new, simpler interface (EpisodePublisher) in front of many classes. Side by side: an adapter wraps one class (ThermoJet) so it fits an interface you already have (ReceiptPrinter); a facade puts one new, simpler interface (EpisodePublisher) in front of many classes.
An adapter fits one class; a facade simplifies many.

When not to use it

When should you skip it? If you own both sides, change one of them. A rename beats a new class (refactoring.guru lists this as the pattern’s cost: “Sometimes it’s simpler just to change the service class so that it matches the rest of your code”). If only one call site will ever talk to the printer, the direct code is fine. The adapter pays off when many callers share it.

And watch what creeps in. Discounts, loyalty points or tax rules don’t belong in an adapter. Once it decides things, it isn’t translating any more. And don’t wrap a library just in case you might switch someday. Write the adapter when a real mismatch shows up, like the one at the café.

Decision: do you own both sides? Change one of them. Will only one call site ever use it? Call it directly. Is there a real interface mismatch shared by many callers? Write a thin adapter. Is business logic creeping into it? Move the rules out. Decision: do you own both sides? Change one of them. Will only one call site ever use it? Call it directly. Is there a real interface mismatch shared by many callers? Write a thin adapter. Is business logic creeping into it? Move the rules out.
Keep it thin.

Keep it thin: one interface out, one class in, and only the conversion in between.

Recap

  • When code you can’t change speaks a different interface, don’t teach every caller its language.
  • Write one adapter that implements your interface and holds their class.
  • Prefer holding over extending. The JDK’s asList is one.
  • It’s not a decorator, which keeps the interface, and not a facade, which simplifies many classes.
  • Keep it thin.
Recap chain: find the mismatch, write one adapter that implements your interface, hold their class inside, keep the conversion thin. Recap chain: find the mismatch, write one adapter that implements your interface, hold their class inside, keep the conversion thin.
Change the shape, not the job.

Checklist:

  • Do several callers talk to a class whose interface doesn’t match yours?
  • Can you change that class? (If yes, change it instead.)
  • Does the adapter implement your interface and hold theirs?
  • Is the adapter only converting, with no business rules inside?
  • Can tests use a fake of your interface instead of the real device or SDK?

Change the shape, not the job.

Related lessons: Decorator, Facade, Polymorphism, Encapsulation.

Further reading