# AdapterTwelve 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.

{{< lesson-video youtube="yjoEhqQU0hM" title="Adapter" >}}

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

```mermaid {alt="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." caption="Every caller speaks the printer's language."}
flowchart LR
  A["checkout"] --> T["ThermoJet<br/>feed(bytes) + cut()"]
  B["refunds"] --> T
  C["kitchen ticket"] --> T
  D["end of day"] --> T
  E["… eight more"] --> T
  N["next year's printer"] -. "all twelve change again" .-> A
  class A,B,C,D,E c4
  class T c1
  class N bad
```

## 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**.

```mermaid {alt="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)." caption="The meeting, mapped onto the code."}
flowchart LR
  A["the team"] --> A2["client: Checkout"]
  B["the team's language"] --> B2["target: ReceiptPrinter"]
  C["the visitor"] --> C2["adaptee: ThermoJet"]
  D["the translator"] --> D2["adapter: ThermoJetPrinter"]
  class A2 c4
  class B2 c6
  class C2 c1
  class D2 c5
```

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

```java
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.

```java
// 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.

```java
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.

```mermaid {alt="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." caption="One fix, twelve edits."}
flowchart LR
  F["fix: US_ASCII to ISO_8859_1"] --> A["checkout: fixed"]
  F --> B["refunds: fixed"]
  F --> C["kitchen ticket: fixed"]
  F --> D["… eight more: fixed"]
  F --> M["split bill: missed"]
  class F hl
  class A,B,C,D good
  class M bad
```

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.

```java
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.

```mermaid {alt="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." caption="Your interface outside, their class inside."}
sequenceDiagram
  participant C as Checkout
  participant A as ThermoJetPrinter
  participant J as ThermoJet
  C->>A: print(three lines)
  Note over A: join, encode as Latin-1
  A->>J: feed(bytes)
  A->>J: cut()
  A-->>C: done
```

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

```java
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.

```java
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**.

```mermaid {alt="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()." caption="Four roles: an object adapter holds the adaptee."}
classDiagram
  class Checkout
  class ReceiptPrinter {
    <<interface>>
    +print(lines)
  }
  class ThermoJetPrinter {
    -jet: ThermoJet
    +print(lines)
  }
  class ThermoJet {
    +feed(bytes)
    +cut()
  }
  Checkout --> ReceiptPrinter : uses
  ReceiptPrinter <|.. ThermoJetPrinter
  ThermoJetPrinter o--> ThermoJet : holds
```

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:

```java
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.

```java
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").

```java
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](/patterns/decorator-pattern/): "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.

| Wrapper | Interface in → out | What it adds |
|---|---|---|
| Decorator | `ReceiptPrinter` → `ReceiptPrinter` | one more job |
| [Proxy](/patterns/proxy-pattern/) | `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](/patterns/facade-pattern/) lesson).

```mermaid {alt="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." caption="An adapter fits one class; a facade simplifies many."}
flowchart LR
  subgraph AD["Adapter"]
    direction TB
    J["ThermoJet"] --> P["ThermoJetPrinter"] --> R["ReceiptPrinter<br/>(an interface you have)"]
  end
  subgraph FA["Facade"]
    direction TB
    S["five subsystem classes"] --> E["EpisodePublisher<br/>(a new, simpler one)"]
  end
  AD ~~~ FA
  class J c1
  class P c5
  class R c6
  class E c6
  class S muted
```

## 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é.

```mermaid {alt="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." caption="Keep it thin."}
flowchart TD
  Q1{"Do you own both sides?"} -->|yes| A1["change one: rename"]
  Q1 -->|no| Q2{"Only one call site?"}
  Q2 -->|yes| A2["call it directly"]
  Q2 -->|no| Q3{"A real mismatch, many callers?"}
  Q3 -->|no| A3["don't wrap just in case"]
  Q3 -->|yes| A4["write a thin adapter"]
  class A4 good
  class A3 muted
```

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.

```mermaid {alt="Recap chain: find the mismatch, write one adapter that implements your interface, hold their class inside, keep the conversion thin." caption="Change the shape, not the job."}
flowchart LR
  A["find the mismatch"] --> B["implement your interface"] --> C["hold their class"] --> D["conversion only"]
  class B c6
  class C c1
  class D good
```

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](/patterns/decorator-pattern/), [Facade](/patterns/facade-pattern/),
[Polymorphism](/fundamentals/polymorphism/), [Encapsulation](/fundamentals/encapsulation/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Adapter.
- refactoring.guru: [Adapter](https://refactoring.guru/design-patterns/adapter).
- [`Arrays.asList`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Arrays.html#asList(T...)) and
  [`Collections.enumeration`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collections.html#enumeration(java.util.Collection)) javadoc.
