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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
Arrays.asList and Collections.enumerationThe 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.
Now a common mix-up: any wrapper is an adapter. Decorators and proxies wrap things too. The difference is the interface.
| Wrapper | Interface in → out | What it adds |
|---|---|---|
| Decorator | ReceiptPrinter → ReceiptPrinter | one more job |
| Proxy | ReceiptPrinter → ReceiptPrinter | guards access |
| Adapter | ReceiptPrinter → ThermoJet | nothing: 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).
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é.
Keep it thin: one interface out, one class in, and only the conversion in between.
asList is one.Checklist:
Change the shape, not the job.
Related lessons: Decorator, Facade, Polymorphism, Encapsulation.
Arrays.asList and
Collections.enumeration javadoc.