Adapter and Facade

Mid-level Frequently asked 4 min

On this page

The question

What is the difference between Adapter and Facade?

30-second answer

An Adapter solves a fit problem: it wraps one class and implements the interface your code already expects, translating each call. A Facade solves a complexity problem: it gives many classes one new, simpler interface and coordinates them behind it. Both are wrappers, so ask what is wrong. If the shape is wrong, adapt it; if there is too much to call, put a Facade in front.

Understand it

Adapter plug vs facade front desk

Compare

Adapter, a travel plug: charge(id, 19.99) does not fit makeCharge(1999, id). The adapter implements the interface your code expects and translates each call.

View as text

A client on the left calls a wrapper in the middle, which reaches the classes on the right. Three rows below compare what it wraps, its goal and its interface.

Adapter, a travel plug: charge(id, 19.99) does not fit makeCharge(1999, id). The adapter implements the interface your code expects and translates each call. One class sits on the right. The rows read one class, make it fit, and one you already expect.

Facade, a front desk: one placeOrder() call stands for four subsystems, in the right order. The caller makes one request, and the facade coordinates the rest. Four classes sit on the right: Inventory, Payments, Shipping and Mailer. The rows read many classes, make it simple, and a new, smaller one.

A client on the left calls a wrapper in the middle, which reaches the classes on the right. Three rows below compare what it wraps, its goal and its interface.

Adapter, a travel plug: charge(id, 19.99) does not fit makeCharge(1999, id). The adapter implements the interface your code expects and translates each call. One class sits on the right. The rows read one class, make it fit, and one you already expect.

Facade, a front desk: one placeOrder() call stands for four subsystems, in the right order. The caller makes one request, and the facade coordinates the rest. Four classes sit on the right: Inventory, Payments, Shipping and Mailer. The rows read many classes, make it simple, and a new, smaller one.

Takeaway: An Adapter makes one class fit an interface you already have. A Facade gives many classes one simpler interface. Ask whether the problem is fit or complexity.

Which wrapper to chooseIf one class has the wrong interface, use an Adapter. If too many classes must be called, use a Facade. If the type is right and you want to add behavior, use a Decorator. If the type is right and you want to control access, use a Proxy.What is wrong?Wrong shape:AdapterToo many classes:FacadeNeeds morebehavior:DecoratorNeeds accesscontrol:Proxy
Which wrapper to chooseIf one class has the wrong interface, use an Adapter. If too many classes must be called, use a Facade. If the type is right and you want to add behavior, use a Decorator. If the type is right and you want to control access, use a Proxy.What is wrong?Wrong shape:AdapterToo many classes:FacadeNeeds morebehavior:DecoratorNeeds accesscontrol:Proxy
Which wrapper: what is the problem?

In code

interface PaymentGateway { boolean charge(String orderId, BigDecimal amount); }

class LegacyPayClient {                                   // third-party: you cannot change it
    int makeCharge(long amountInCents, String reference) { return 0; }   // 0 means OK
}

class LegacyPayAdapter implements PaymentGateway {
    private final LegacyPayClient client;

    LegacyPayAdapter(LegacyPayClient client) { this.client = client; }

    @Override public boolean charge(String orderId, BigDecimal amount) {
        long cents = amount.movePointRight(2).longValueExact();
        return client.makeCharge(cents, orderId) == 0;
    }
}
Adapter: the legacy client fits the interface your code already uses
class CheckoutFacade {
    private final Inventory inventory;
    private final PaymentGateway payments;
    private final Shipping shipping;
    private final Mailer mailer;

    CheckoutFacade(Inventory inventory, PaymentGateway payments, Shipping shipping, Mailer mailer) {
        this.inventory = inventory;
        this.payments = payments;
        this.shipping = shipping;
        this.mailer = mailer;
    }

    String placeOrder(String orderId, Item item, BigDecimal amount) {
        inventory.reserve(item);
        if (!payments.charge(orderId, amount)) throw new IllegalStateException("payment declined");
        String tracking = shipping.schedule(orderId);
        mailer.confirm(orderId, tracking);
        return tracking;
    }
}
Facade: one call stands for four subsystems, in the right order
The Adapter in class formCheckout depends on the PaymentGateway interface. LegacyPayAdapter implements PaymentGateway and calls LegacyPayClient, which Checkout never sees.«interface»PaymentGateway+charge(orderId, amount)LegacyPayClient+makeCharge(cents, reference)CheckoutLegacyPayAdapter
The Adapter in class formCheckout depends on the PaymentGateway interface. LegacyPayAdapter implements PaymentGateway and calls LegacyPayClient, which Checkout never sees.«interface»PaymentGateway+charge(orderId, amount)LegacyPayClient+makeCharge(cents, reference)CheckoutLegacyPayAdapter
The Adapter in class form
Enumeration<String> legacy = vector.elements();
Iterator<String> it = legacy.asIterator();     // Java 9: an adapter object, nothing is copied
while (it.hasNext()) System.out.println(it.next());
The JDK (Java Development Kit) adapts its old Enumeration to the Iterator interface

Solve it

Integrate a shipping vendor’s SDK (software development kit) without letting it leak into your code

The vendor SDK quotes rates from a weight in pounds passed as a String, returns its own VendorRate DTO (data transfer object) and throws a checked VendorException. Booking takes four calls: login, rate, select and confirm. Your domain works in kilograms and Money.

  1. Define the port in your terms. ShippingRates.quote(Parcel) returns Money and throws your own ShippingUnavailableException. The domain depends only on it.
  2. Adapt. VendorShippingAdapter converts kilograms to the vendor’s pound string, VendorRate to Money and VendorException to your exception.
  3. Wrap the sequence. Hiding login, rate, select and confirm behind one book() call is a Facade, the second half of the same class.
  4. Contain the vendor. Only the adapter imports the vendor package, so a vendor change is a one-class change.
  5. Check. Test the adapter against the vendor’s sandbox; test the domain with a fake ShippingRates.
interface ShippingRates { Money quote(Parcel parcel); }

class VendorShippingAdapter implements ShippingRates {
    private static final BigDecimal LB_PER_KG = new BigDecimal("2.20462");
    private final VendorClient vendor;
    VendorShippingAdapter(VendorClient vendor) { this.vendor = vendor; }

    @Override public Money quote(Parcel parcel) {
        String pounds = parcel.kg().multiply(LB_PER_KG).setScale(2, RoundingMode.HALF_UP).toPlainString();
        try {
            VendorRate rate = vendor.rate(pounds);
            return Money.of(rate.amountCents(), rate.currency());
        } catch (VendorException e) {
            throw new ShippingUnavailableException("vendor rate failed", e);
        }
    }
}
Translate units, types and errors at the boundary

How to answer

  • Adapter: one class, an existing interface, and translation of arguments and results.
  • Facade: many classes, a new interface, and coordination of calls.
  • A Facade does not stop anyone from using the subsystem directly when they need more.

Common mistakes

  • Treating any wrapper as an Adapter, even when no interface is being matched.
  • Letting a Facade grow into a class that holds all the business logic.

Follow-up questions

How would you integrate a legacy or third-party API so it does not spread through your code?

Define an interface in your own terms, such as PaymentGateway, and write one Adapter that implements it by calling the third-party client. The Adapter converts types and maps error codes to your exceptions. Only it imports the vendor's classes, so a new vendor means one new Adapter, and tests can use a fake gateway without any network.

  • Name the interface after your needs, not the vendor's API.
  • Convert vendor errors and status codes at the boundary.
  • In Domain-Driven Design, this boundary is called an anti-corruption layer.

See it in the infographic: Adapter plug vs facade front desk

How is an Adapter different from a Decorator?

Look at the interface. An Adapter changes it: the wrapped class has one interface and the wrapper exposes a different one. A Decorator keeps it: wrapper and target have the same type, which is why decorators can stack. A Proxy also keeps it. If the caller could use the wrapped object directly, the wrapper is not an Adapter.

  • Adapter changes the type and keeps the behavior.
  • Decorator keeps the type and adds behavior.
  • Proxy keeps the type and controls access.

See it in the infographic: Adapter plug vs facade front desk

What can go wrong with a Facade?

It can turn into a god class that knows every subsystem and collects unrelated methods. It can hide details that a caller really needs, such as a transaction boundary. And if it only forwards one call to one class, it adds nothing at all. Keep it thin: it should coordinate, while the rules stay in the subsystems.

  • Split a Facade that serves unrelated use cases.
  • One method that forwards to one class is just indirection.
  • Tests should still cover the subsystems directly.

See it in the infographic: Adapter plug vs facade front desk

Where does the JDK use Adapter?

InputStreamReader adapts a byte InputStream to a character Reader, so code expecting a Reader can read bytes. Arrays.asList adapts an array to a List view, so writing to the array shows in the list. Both change the interface and leave the underlying object where it is.

Is a Spring service layer a Facade?

It often acts as one: a controller calls one service method, and the service coordinates repositories and clients behind it. It is a Facade when it mainly orchestrates. If it also holds the business rules, it is doing more than the pattern describes, so name the rules and consider moving them into the domain.

Check yourself

1. Your code calls charge(id, amount), and a vendor library only offers makeCharge(cents, reference). You cannot change the library. Which pattern fits?
Show answers
  • Adapter: Correct. One class has the wrong shape, so a wrapper implements your interface and translates the call.
  • Facade: Incorrect. A Facade simplifies many classes; here one class has the wrong interface.
  • Decorator: Incorrect. A Decorator keeps the same interface, and this call needs a different one.
2. Placing an order means calling inventory, payments, shipping and mail in the right order, from five controllers. Which pattern removes the repetition?
Show answers
  • Facade: Correct. One placeOrder() method coordinates the subsystems, so the controllers make a single call.
  • Adapter: Incorrect. Nothing has the wrong interface; the trouble is how many calls each caller has to make.
  • Singleton: Incorrect. Limiting instances does not reduce how many subsystems each controller must call.