Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 57 ยท Structural Patterns

Adapter

Learn the Adapter design pattern: wrap an incompatible interface so it fits yours, with legacy API and payment gateway examples and the object vs class forms.

The Adapter pattern converts the interface of an existing class into the interface your code expects. It is the software version of a travel plug adapter: the wall socket and your laptop charger both work fine, they simply do not fit together, so a small piece in the middle translates.

You reach for an adapter when you want to use a class, library or service that does the right job but has the wrong shape: different method names, different argument order, different units, different data formats. You cannot (or should not) edit that code, since it may be a third-party library, a legacy system or a vendor SDK. So you leave it alone and write a thin wrapper that speaks your interface on the outside and the foreign one on the inside. Adapter is the main tool for keeping outside code from leaking into your design, following the Dependency Inversion Principle.

Three roles

Target The interface your client expects.
Adaptee The existing class with a different interface.
Adapter Implements Target by calling the Adaptee.

The client never learns the Adaptee exists.

1 / 2

The structure

The client talks to a Target interface. The adapter implements that interface and internally calls the Adaptee, translating arguments and results as needed.

classDiagram
    class Target {
        <<interface>>
        +request()
    }
    class Adapter {
        -adaptee
        +request()
    }
    class Adaptee {
        +specificRequest()
    }
    class Client
    Client --> Target
    Target <|.. Adapter
    Adapter --> Adaptee : delegates to

The client calls request(); the adapter turns it into a call to specificRequest().

Example: a legacy API

Imagine your reporting code expects a temperature sensor with readCelsius(). The only sensor library you can buy reports in Fahrenheit through a method called fetchReading(), returning a string like "72.5F". You write an adapter.

JS Adapting a legacy sensor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

reportTemperature is unchanged whether the sensor is modern or legacy. If the vendor later switches to a JSON format, only the adapter changes. That is the practical value: one place absorbs the mismatch.

Example: payment gateways

Adapters shine when several outside services do the same job in different ways. Suppose your shop must accept payments through two providers. One expects an amount in dollars and returns { ok: true }; the other expects cents and returns a status string. Your code should not care.

The adapters below implement one target method, pay(amountCents, customerId), and always return the same result shape. The "SDKs" are invented stand-ins for vendor libraries, which cannot run here.

JS One interface for two payment providers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Adding a third provider is one new adapter, with no edits to checkout. This also makes testing easier: a FakeGatewayAdapter that returns canned results lets you test checkout without touching the network. The adapters are the only classes that import vendor code, which also makes it cheap to swap vendors later.

Object adapter versus class adapter

The GoF book describes two forms:

  • Object adapter: the adapter has an adaptee (composition) and forwards calls to it. This is what both examples above do. It works in every language, can adapt a whole class hierarchy because the adaptee is just a reference, and follows "favor composition over inheritance".
  • Class adapter: the adapter inherits from the adaptee and implements the target, so it is both at once. It needs multiple inheritance or inheriting a class plus implementing an interface. It is natural in C++ (private inheritance from the adaptee, public inheritance from the target) and possible in Java only when the target is an interface. It avoids one level of indirection and can override adaptee behavior, but it is tied to one concrete adaptee class.

A read-only C++ class adapter:

C++
class Target {
public:
    virtual ~Target() = default;
    virtual double readCelsius() = 0;
};

class LegacySensor {                       // the adaptee
public:
    std::string fetchReading() { return "212F"; }
};

// Class adapter: is-a Target, and privately is-a LegacySensor.
class SensorAdapter : public Target, private LegacySensor {
public:
    double readCelsius() override {
        double f = std::stod(fetchReading());   // stod stops at the 'F'
        return (f - 32.0) * 5.0 / 9.0;
    }
};

Prefer the object adapter unless you have a concrete reason, such as needing to override some behavior of the adaptee.

Adapter variants: two-way and interface (default) adapters

Two more shapes of the pattern show up often. Their names are confusingly close, but the problems they solve are very different.

Two-way adapter

A normal adapter is one-way: the client uses the target interface and the adapter translates to the adaptee. Sometimes both worlds already have code that expects its own interface, and each side must be able to use the other's objects. A two-way adapter implements both interfaces and translates in both directions, so the same object can be handed to code written for either side.

A common case is a system migrating from one API to another, where old and new modules must work side by side for a while. In the example, the old code measures in Fahrenheit through readF(), while the new code expects Celsius through readC(). One sensor class serves both.

JS A two-way temperature adapter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The adapter stores the reading in one canonical unit and exposes both views, so the two conversions cannot drift apart. The price is that the adapter now knows both interfaces, so it is best as a temporary bridge during a migration, or when two long-lived subsystems truly need each other's objects. Make sure the translation round-trips without loss; if one direction loses information (rounding, missing fields), keep a one-way adapter.

Interface (default) adapter

The second variant solves a different problem. Some interfaces are wide: a window-listener interface with seven callbacks, an event handler with a dozen. A class that cares about one callback should not have to write the other six empty methods. An interface adapter (also called a default adapter or skeleton implementation) is a class that implements the whole wide interface with empty or default behavior. Clients extend it and override only the methods they need.

This is where the Java names MouseAdapter and WindowAdapter come from, and it is the idea behind AbstractList. In JavaScript you can build the same thing with a base class or by merging handlers over a table of no-ops.

JS A default adapter for a wide listener interface

Press Run (or Ctrl + Enter) to see the console output here.

No output.

download can call all five methods on every listener without checking which ones exist, because the adapter guarantees they do. Modern languages have other ways to get the same effect: default methods on Java and C# interfaces, optional properties in TypeScript, or simply passing an object that has only the handlers you want and letting the caller skip missing ones. All of them avoid forcing clients to write empty methods.

Two-way adapter Interface (default) adapter
Problem Two sides each expect their own interface A wide interface forces clients to implement unused methods
Implements Both interfaces, translating each way One interface, with empty or default methods
Translates between types? Yes No, it is a convenience base class
Closest to the GoF Adapter? Yes Only by name, it is closer to Template Method's hooks
  • Java's Arrays.asList(array) adapts an array to the List interface; InputStreamReader adapts a byte stream to a character reader.
  • Python's io.TextIOWrapper adapts a binary stream to a text stream.
  • In front-end code, a small function that turns an API's snake_case JSON into your app's camelCase model is an adapter.
  • Database drivers: SQLAlchemy dialects and JDBC drivers adapt vendor protocols to one API.

How does Adapter differ from its neighbors? A Facade simplifies a whole subsystem behind a new, easier interface, while an adapter makes one existing interface match another existing one. A Decorator keeps the interface the same and adds behavior. A Proxy also keeps the interface the same and controls access. A Bridge is designed up front to let two hierarchies vary independently, whereas Adapter is applied afterwards to make things that already exist work together.

Pitfalls

  • Leaky adapters: if exceptions, types or concepts of the vendor SDK escape through the adapter, the client is coupled to it again. Translate errors and data into your own types.
  • Fat adapters: an adapter that adds business rules stops being an adapter. Keep it a translator.
  • Adapting everything: when you control both sides, change one of them instead of adding a layer.
  • Lossy mappings: if the adaptee cannot support part of the target (say, refunds), decide explicitly: throw a clear "not supported" error rather than silently doing nothing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Adapter pattern do?

    An adapter implements the interface the client expects and forwards calls to an existing class with a different interface.
  2. 2. In the object adapter form, how does the adapter reuse the adaptee?

    The object adapter wraps an adaptee instance, which works in any language and can adapt subclasses of the adaptee too.
  3. 3. Why adapt each payment provider behind one interface?

    A common target interface isolates vendor-specific code in the adapters and makes substitution and testing easy.
  4. 4. How is a Facade different from an Adapter?

    Facade is about simplification of many parts; Adapter is about compatibility between two interfaces.
  5. 5. Which problem indicates a leaky adapter?

    When vendor types escape, the client depends on the vendor again, which defeats the purpose of the adapter.

Summary

  • An adapter implements the interface your client expects and translates calls to an existing class that has a different interface.
  • Use it for legacy code, third-party libraries and vendors such as payment gateways, without editing them.
  • Object adapters use composition and work everywhere; class adapters use inheritance and fit C++-style multiple inheritance.
  • Keep adapters thin, translate errors and data into your own types, and let only adapters import vendor code.
  • Adapter makes interfaces match, Facade simplifies a subsystem, Decorator adds behavior, Proxy controls access.

Next lesson: Bridge.