How do I implement the Adapter pattern in Java?

Adapter Structural Pattern

A reporting application saves text through a TextStorage interface. An existing archive component accepts a byte array followed by an entry name. To reuse it, we need to translate the application’s text-based call into the archive’s byte-based call.

Adapter is a Gang of Four structural pattern that makes an existing component usable through an interface expected by a client. An object adapter holds a reference to that component and translates requests before delegating to it. The GoF discuss object composition and adaptation in their structural patterns chapter. Design Patterns, Chapter 4

This article begins the structural patterns section after the creational patterns series, which covered Singleton, Factory Method, Abstract Factory, Builder, and Prototype.

A complete example

Save the following code as AdapterExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.adapter;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class AdapterExample {
    interface TextStorage {
        void save(String fileName, String text);
    }

    static final class LegacyArchive {
        void store(byte[] data, String entryName) {
            System.out.println("Archived: " + entryName);
            System.out.println("UTF-8 bytes: " + data.length);
            System.out.println("Content: " + new String(data, StandardCharsets.UTF_8));
        }
    }

    static final class ArchiveAdapter implements TextStorage {
        private final LegacyArchive archive;

        ArchiveAdapter(LegacyArchive archive) {
            this.archive = Objects.requireNonNull(archive);
        }

        @Override
        public void save(String fileName, String text) {
            Objects.requireNonNull(fileName);
            Objects.requireNonNull(text);
            byte[] data = text.getBytes(StandardCharsets.UTF_8);
            archive.store(data, fileName);
        }
    }

    static final class ReportService {
        private final TextStorage storage;

        ReportService(TextStorage storage) {
            this.storage = Objects.requireNonNull(storage);
        }

        void exportReport() {
            storage.save("sales.txt", "Revenue: 1200 EUR");
        }
    }

    public static void main(String[] args) {
        LegacyArchive archive = new LegacyArchive();
        TextStorage storage = new ArchiveAdapter(archive);
        ReportService service = new ReportService(storage);
        service.exportReport();
    }
}

Compile and run it from the directory containing the source file.

javac -d out AdapterExample.java
java -cp out org.kodejava.pattern.adapter.AdapterExample

The output shows the archive receiving the entry name and encoded content.

Archived: sales.txt
UTF-8 bytes: 17
Content: Revenue: 1200 EUR

The archive component prints its received data to keep the example self-contained. A production archive implementation would persist the bytes.

How the adapter connects the interfaces

GoF role Example Responsibility
Target TextStorage Defines the interface expected by the application.
Adaptee LegacyArchive Provides the existing byte-oriented operation.
Adapter ArchiveAdapter Implements the target and translates calls to the adaptee.
Client ReportService Saves its report through the target interface.

The client calls save(fileName, text). The adapter encodes the text as UTF-8, puts the arguments in the order expected by store(data, entryName), then delegates to the archive instance supplied to its constructor.

The encoding is part of the adapter’s contract. Callers supply text, while the archive receives UTF-8 bytes. Both sides must agree on that representation when the content is read later.

The application setup in main() knows which archive and adapter to create. ReportService receives only a TextStorage, so its export operation works through the application’s interface.

The adapter uses composition by holding the existing component in a field. This also allows it to wrap the final LegacyArchive class shown here.

Recognizing adaptation in Java APIs

As another example of interface adaptation, consider InputStreamReader. It accepts a byte stream and exposes character-reading operations through Reader, decoding with a charset. Java documents the byte-to-character conversion. Viewing that conversion as an adapter is a design interpretation of its API. InputStreamReader documentation

When should I use Adapter?

Use Adapter when application code expects an interface that an existing library, vendor SDK, or legacy component does not implement. It provides a dedicated place for translating method signatures, representations, and conventions.

Before implementing one, define the behavior the target promises. Consider character encodings, validation, ownership of resources, and how errors reach the caller. A successful method translation also needs to preserve those behavioral expectations.

The tradeoff is an additional class to maintain as either API changes. Adaptation can also expose a deeper mismatch. For example, a target that promises atomic writes needs a backing implementation capable of honoring that promise, or an adapter that supplies the missing behavior.

In this example, the target contract is deliberately small. It accepts a non-null file name and text, and the adapter forwards the corresponding UTF-8 bytes. A larger storage contract would need explicit rules for overwrites, failures, and persistence.

Next, we will cover Bridge.