SyntaxPilot
Courses/Low-Level Design/Lesson 27

Low-Level Design · Lesson 27 of 90 · 10 min

Adapter pattern

Adapter patterntarget interfaceadapteeadapterobject adapterclass adapterwrapperlegacy integrationthird-party SDK adaptationtwo-way adapterArrays.asList as adapter

These are the notes for Low-Level Design (LLD) episode 27, the first of the structural patterns. Creational patterns were about creating objects; structural patterns are about how classes and objects are connected to form bigger structures. The Adapter solves a problem you will meet in every real job: you need to use some code, but its methods don't match the ones your code expects. We start with a phone charger that doesn't fit a UK socket, watch a bank's SDK fail to compile in Priya's checkout, write the obvious hack and charge a customer a hundred times too much, then invent the adapter: a small wrapper class that implements the interface the client expects (the target) and translates every call to the existing class (the adaptee). Then object adapter vs class adapter, Arrays.asList as an adapter, two-way adapters, legacy integration, and how Adapter differs from Decorator and Facade. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life idea: an Indian charger in a UK socket

On a trip In code
Asha's Indian charger (round pins) The client: code that expects one particular interface
The UK wall socket: good power, wrong shape The adaptee: a useful class whose interface doesn't fit
A travel adapter: round holes in, flat pins out The adapter: translates one interface into another
Nothing rewired: not the charger, not the wall No edits to either side; only the small thing in the middle is new

2. The problem: the bank's SDK doesn't fit

Priya's checkout expects a PaymentGateway: one method pay(int paise, String upiId). A UPI ID is a payment address like asha@upi; one rupee is 100 paise. SimplePay is the gateway she uses today.

A bank offers lower fees and gives her its SDK. An SDK (software development kit) is ready-made code a company gives you so you can use its service. The bank's method is transfer(double rupees, String vpa): a different name, rupees as a decimal number, the UPI ID called a VPA (virtual payment address), and a boolean result. It is third-party code: it belongs to the bank, so we can't edit it.

interface PaymentGateway { String pay(int paise, String upiId); }    // what checkout expects
class SimplePay implements PaymentGateway {                            // the gateway we have today
    public String pay(int paise, String upiId) { return "SimplePay: Rs " + paise / 100 + " from " + upiId; }
}
class BankSdk {                                     // a bank's SDK: we can't edit this code
    public boolean transfer(double rupees, String vpa) {
        System.out.println("BankSdk: sent Rs " + rupees + " from " + vpa);
        return true;
    }
}
public class Main {
    static void checkout(PaymentGateway g) {            // Priya's checkout: Rs 240 = 24000 paise
        System.out.println(g.pay(24000, "asha@upi"));
    }
    public static void main(String[] args) {
        checkout(new SimplePay());
        checkout(new BankSdk());                         // the new bank
    }
}
Main.java:17: error: incompatible types: BankSdk cannot be converted to PaymentGateway
        checkout(new BankSdk());                         // the new bank
                 ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

BankSdk works fine; it just isn't a PaymentGateway. Round pins, flat socket.

3. The obvious hack: call the SDK directly

interface PaymentGateway { String pay(int paise, String upiId); }    // what checkout expects
class SimplePay implements PaymentGateway {                            // the gateway we have today
    public String pay(int paise, String upiId) { return "SimplePay: Rs " + paise / 100 + " from " + upiId; }
}
class BankSdk {                                     // a bank's SDK: we can't edit this code
    public boolean transfer(double rupees, String vpa) {
        System.out.println("BankSdk: sent Rs " + rupees + " from " + vpa);
        return true;
    }
}
public class Main {
    static void checkout(Object g) {                     // the hack: accept anything
        if (g instanceof BankSdk b) {
            b.transfer(24000, "asha@upi");                // forgot: paise, not rupees
        } else {
            System.out.println(((PaymentGateway) g).pay(24000, "asha@upi"));
        }
    }
    public static void main(String[] args) {
        checkout(new SimplePay());
        checkout(new BankSdk());
    }
}
SimplePay: Rs 240 from asha@upi
BankSdk: sent Rs 24000.0 from asha@upi

Checkout now accepts any Object and uses instanceof (with a pattern variable b, episode 9) to call the SDK directly. The order is Rs 240 = 24000 paise, but the hack passed paise to a method that wants rupees: Rs 24000, a hundred times too much. It compiled, because both are numbers.

Why the hack failed

  • The two sides speak different interfaces: a different method name, different units, a different parameter name, and a different result type.
  • The translation was done inside checkout, by hand, and got wrong; every place that pays would need the same conversion.
  • Every new bank means another instanceof branch in checkout, which breaks the Open-Closed Principle (episode 13: add behaviour without editing existing code).

We want one small class that translates, in one place, so neither side changes.

4. The fix: an adapter

interface PaymentGateway { String pay(int paise, String upiId); }    // what checkout expects
class SimplePay implements PaymentGateway {                            // the gateway we have today
    public String pay(int paise, String upiId) { return "SimplePay: Rs " + paise / 100 + " from " + upiId; }
}
class BankSdk {                                     // a bank's SDK: we can't edit this code
    public boolean transfer(double rupees, String vpa) {
        System.out.println("BankSdk: sent Rs " + rupees + " from " + vpa);
        return true;
    }
}
class BankSdkAdapter implements PaymentGateway {        // the adapter
    private final BankSdk sdk;                           // wraps the adaptee
    BankSdkAdapter(BankSdk sdk) { this.sdk = sdk; }
    public String pay(int paise, String upiId) {
        boolean ok = sdk.transfer(paise / 100.0, upiId);    // translate: paise -> rupees, name, result
        return ok ? "BankSdk: payment done" : "BankSdk: payment failed";
    }
}
public class Main {
    static void checkout(PaymentGateway g) {            // Priya's checkout: Rs 240 = 24000 paise
        System.out.println(g.pay(24000, "asha@upi"));
    }
    public static void main(String[] args) {
        checkout(new SimplePay());
        checkout(new BankSdkAdapter(new BankSdk()));     // checkout is not changed
    }
}
SimplePay: Rs 240 from asha@upi
BankSdk: sent Rs 240.0 from asha@upi
BankSdk: payment done
  • BankSdkAdapter implements PaymentGateway, so it fits wherever a gateway is expected.
  • It holds a BankSdk in a field and forwards (delegates) each call to it. An object that holds another object and changes how you talk to it is a wrapper; the Adapter pattern is also known as the Wrapper pattern.
  • pay() does the whole translation in one place: paise / 100.0 gives rupees (the .0 makes it a double division, so 24050 paise would become 240.5, not 240), upiId is passed as the VPA, and true/false becomes a message.
  • Checkout is unchanged: it takes a PaymentGateway again and doesn't know a bank SDK exists.

5. It has a name: the Adapter pattern

Intent: convert the interface of a class into another interface that clients expect, so classes with incompatible interfaces can work together.

Role In our code Job
Target PaymentGateway The interface the client expects
Client checkout() Uses only the target
Adaptee BankSdk The existing class with the wrong interface
Adapter BankSdkAdapter Implements the target, translates calls to the adaptee

This is programming to an interface (episode 7) paying off: because checkout depends on PaymentGateway, any new provider needs only a new adapter.

6. Object adapter vs class adapter

What we built is an object adapter: it implements the target and holds the adaptee (composition, has-a). It delegates at runtime. The other kind is the class adapter: it extends the adaptee class and implements the target (inheritance, is-a):

interface PaymentGateway { String pay(int paise, String upiId); }    // what checkout expects
class SimplePay implements PaymentGateway {                            // the gateway we have today
    public String pay(int paise, String upiId) { return "SimplePay: Rs " + paise / 100 + " from " + upiId; }
}
class BankSdk {                                     // a bank's SDK: we can't edit this code
    public boolean transfer(double rupees, String vpa) {
        System.out.println("BankSdk: sent Rs " + rupees + " from " + vpa);
        return true;
    }
}
class BankSdkClassAdapter extends BankSdk implements PaymentGateway {   // class adapter
    public String pay(int paise, String upiId) {
        return transfer(paise / 100.0, upiId) ? "payment done" : "payment failed";   // inherited method
    }
}
public class Main {
    static void checkout(PaymentGateway g) {            // Priya's checkout: Rs 240 = 24000 paise
        System.out.println(g.pay(24000, "asha@upi"));
    }
    public static void main(String[] args) {
        checkout(new BankSdkClassAdapter());
    }
}
BankSdk: sent Rs 240.0 from asha@upi
payment done

It works, and needs no field, because transfer is inherited. But when the bank ships version 2 with final class BankSdk (a final class can't be extended, episode 8):

interface PaymentGateway { String pay(int paise, String upiId); }    // what checkout expects
class SimplePay implements PaymentGateway {                            // the gateway we have today
    public String pay(int paise, String upiId) { return "SimplePay: Rs " + paise / 100 + " from " + upiId; }
}
final class BankSdk {                                     // version 2 of the SDK is final 
    public boolean transfer(double rupees, String vpa) {
        System.out.println("BankSdk: sent Rs " + rupees + " from " + vpa);
        return true;
    }
}
class BankSdkClassAdapter extends BankSdk implements PaymentGateway {   // class adapter
    public String pay(int paise, String upiId) {
        return transfer(paise / 100.0, upiId) ? "payment done" : "payment failed";   // inherited method
    }
}
public class Main {
    static void checkout(PaymentGateway g) {            // Priya's checkout: Rs 240 = 24000 paise
        System.out.println(g.pay(24000, "asha@upi"));
    }
    public static void main(String[] args) {
        checkout(new BankSdkClassAdapter());
    }
}
Main.java:11: error: cannot inherit from final BankSdk
class BankSdkClassAdapter extends BankSdk implements PaymentGateway {   // class adapter
                                  ^
1 error
Object adapter Class adapter
How implements Target, holds an Adaptee field extends Adaptee implements Target
Relationship has-a (composition) is-a (inheritance)
Final adaptee class works error: cannot inherit from final ...
Adapts subclasses of the adaptee yes: pass any subclass object no: fixed to one class
Swap the adaptee at runtime yes no
Java limits none a class can extend only one class
Can override adaptee behaviour no (only wrap it) yes

Prefer the object adapter (composition over inheritance, episode 11). Write it in interviews.

7. Adapters inside Java: Arrays.asList

Arrays.asList(array) returns a fixed-size List backed by the array: it doesn't copy, it wraps the same array so it looks like a List. The array is the adaptee, List is the target.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[] menu = {"dosa", "idli", "vada"};          // an array: the adaptee
        List<String> list = Arrays.asList(menu);           // the same array, seen as a List
        System.out.println(list + ", size " + list.size() + ", has idli? " + list.contains("idli"));
        list.set(0, "masala dosa");                         // writes through to the array
        System.out.println("menu[0] = " + menu[0]);
        list.add("upma");                                   // an array can't grow
    }
}
[dosa, idli, vada], size 3, has idli? true
menu[0] = masala dosa
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:155)
    at java.base/java.util.AbstractList.add(AbstractList.java:113)
    at Main.main(Main.java:10)
  • size(), contains() and toString() work: they are List methods translated onto the array.
  • set(0, ...) writes through to the array: menu[0] changed, so it is a view, not a copy.
  • add() throws UnsupportedOperationException: an array has a fixed size, so this adapter can't offer that part of List. An adapter can only translate what the adaptee can actually do. To get a growable list, copy it: new ArrayList<>(Arrays.asList(menu)).

Other adapter-style APIs in the JDK: InputStreamReader turns a byte stream (InputStream) into a character Reader; Collections.list(enumeration) turns an old Enumeration into an ArrayList.

8. Third-party SDKs and legacy integration

Third-party SDK adaptation. Wrap every external SDK (payments, maps, SMS, email) behind your own interface and one adapter per provider. Benefits: switching provider means writing one new adapter; the provider's names and units never leak into your code; tests can pass a fake implementation that never calls the real service.

Legacy integration. Legacy code is old code that still runs the business, often with old names and conventions that are risky to change. An adapter lets new code use it through a new, clean interface while the old code stays untouched:

interface Notifier { void notify(String userId, String message); }   // the new interface (target)

class LegacySmsSender {                                               // 2015 code (adaptee): don't touch
    void sendSMS(String mobileWithCode, String text, int priority) {
        System.out.println("SMS to " + mobileWithCode + " [p" + priority + "]: " + text);
    }
}
class LegacySmsAdapter implements Notifier {
    private final LegacySmsSender old;
    private final java.util.Map<String, String> phones;                   // userId -> phone number
    LegacySmsAdapter(LegacySmsSender old, java.util.Map<String, String> phones) { this.old = old; this.phones = phones; }
    public void notify(String userId, String message) {
        old.sendSMS("+91" + phones.get(userId), message, 1);              // translate id -> number, add defaults
    }
}
public class Main {
    public static void main(String[] args) {
        Notifier n = new LegacySmsAdapter(new LegacySmsSender(), java.util.Map.of("u7", "9876543210"));
        n.notify("u7", "Your thali is out for delivery");
    }
}
SMS to +919876543210 [p1]: Your thali is out for delivery

9. Two-way adapters

Sometimes old code and new code both need to use the same object during a migration. A two-way adapter implements both interfaces, so each side talks to it in its own language and both see the same data:

import java.util.*;

interface LegacyCart { void addItem(String name, int paise); int totalPaise(); }   // old screens use this
record Item(String name, double rupees) { }
interface Cart { void add(Item item); List<Item> items(); }                       // new screens use this

class CartBridge implements LegacyCart, Cart {                                    // two-way adapter
    private final List<Item> items = new ArrayList<>();
    public void addItem(String name, int paise) { items.add(new Item(name, paise / 100.0)); }  // old -> new
    public int totalPaise() { return (int) Math.round(items.stream().mapToDouble(Item::rupees).sum() * 100); }
    public void add(Item item) { items.add(item); }                                // new side
    public List<Item> items() { return List.copyOf(items); }
}
public class Main {
    public static void main(String[] args) {
        CartBridge cart = new CartBridge();
        LegacyCart oldScreen = cart;  Cart newScreen = cart;                      // one object, two interfaces
        oldScreen.addItem("Masala dosa", 9000);
        newScreen.add(new Item("Filter coffee", 40.0));
        System.out.println("new screen sees: " + newScreen.items());
        System.out.println("old screen total: " + oldScreen.totalPaise() + " paise");
    }
}
new screen sees: [Item[name=Masala dosa, rupees=90.0], Item[name=Filter coffee, rupees=40.0]]
old screen total: 13000 paise

10. Adapter vs Decorator vs Facade

All three wrap something, so ask: what does the wrapper change?

Pattern Changes Example
Adapter the interface (same job, different names/units) BankSdkAdapter makes transfer(rupees, vpa) look like pay(paise, upiId)
Decorator (episode 28) behaviour, keeping the same interface a LoggingGateway implements PaymentGateway that logs, then calls the real one
Facade (episode 30) complexity: one simple front for many classes one placeOrder() call hiding cart, payment, kitchen and delivery classes
Proxy (episode 29) access to an object, same interface load lazily, check permissions, cache

Common mistakes

Mistake Exact message / symptom Why Fix
Passing the SDK where the interface is expected error: incompatible types: BankSdk cannot be converted to PaymentGateway It doesn't implement the target Wrap it in an adapter
Converting units in the client no error: BankSdk: sent Rs 24000.0 Translation scattered and forgotten Convert once, inside the adapter
Integer division in the conversion no error: 24050 / 100 gives 240, losing 50 paise int / int drops the fraction Divide by 100.0 (or use BigDecimal for money)
Class adapter on a final class error: cannot inherit from final BankSdk Final classes can't be extended Use an object adapter
Arrays.asList(...).add(x) java.lang.UnsupportedOperationException The list is a fixed-size view of an array new ArrayList<>(Arrays.asList(...))
Adapter that adds business logic no error: discounts hidden in a "translator" Mixing responsibilities (episode 12) Keep adapters to translation only
Letting SDK types leak into your interface no error: pay(BankSdkRequest r) Your code now depends on the bank Target uses only your own types

Mini project: two SMS providers behind one interface

Your app sends OTP messages through an Sms interface: void send(String phone, String text). Provider A's SDK has int push(String text, String to) (returns a status code, 200 = sent). Provider B's SDK has boolean deliver(String countryCode, String number, String body). Write an adapter for each, send one message through each, and a fake Sms for tests that records messages instead of sending them.

Solution
import java.util.*;

interface Sms { void send(String phone, String text); }                       // target

class TextLineSdk { public int push(String text, String to) { System.out.println("TextLine -> " + to + ": " + text); return 200; } }
class SignalHubSdk { public boolean deliver(String cc, String number, String body) { System.out.println("SignalHub -> " + cc + " " + number + ": " + body); return true; } }

class TextLineAdapter implements Sms {
    private final TextLineSdk sdk; TextLineAdapter(TextLineSdk sdk) { this.sdk = sdk; }
    public void send(String phone, String text) {
        int code = sdk.push(text, phone);                                    // arguments in the SDK's order
        if (code != 200) throw new IllegalStateException("TextLine failed: " + code);
    }
}
class SignalHubAdapter implements Sms {
    private final SignalHubSdk sdk; SignalHubAdapter(SignalHubSdk sdk) { this.sdk = sdk; }
    public void send(String phone, String text) {                            // phone like +919876543210
        if (!sdk.deliver(phone.substring(0, 3), phone.substring(3), text)) throw new IllegalStateException("SignalHub failed");
    }
}
class FakeSms implements Sms {                                               // for tests
    final List<String> sent = new ArrayList<>();
    public void send(String phone, String text) { sent.add(phone + ": " + text); }
}
public class Main {
    static void sendOtp(Sms sms, String phone) { sms.send(phone, "Your OTP is 4821"); }   // client
    public static void main(String[] args) {
        sendOtp(new TextLineAdapter(new TextLineSdk()), "+919876543210");
        sendOtp(new SignalHubAdapter(new SignalHubSdk()), "+919876543210");
        FakeSms fake = new FakeSms();
        sendOtp(fake, "+910000000000");
        System.out.println("fake recorded: " + fake.sent);
    }
}
TextLine -> +919876543210: Your OTP is 4821
SignalHub -> +91 9876543210: Your OTP is 4821
fake recorded: [+910000000000: Your OTP is 4821]

sendOtp never changes; each provider is one adapter, and the fake makes tests free and fast. (The provider names are made up.)

Practice

1. In the quiz SDK, push(String text, String to) has its arguments in the opposite order to send(String phone, String text). What is the one line inside send?

Answer

sdk.push(text, phone); Swapping argument order is a typical adapter job, and it lives in exactly one place.

2. Add a second bank, UpiBankSdk with String collect(long paise, String handle) that returns "OK" or an error text. Which existing classes change?

Answer

None. Write UpiBankAdapter implements PaymentGateway that calls collect(paise, upiId) and turns "OK" into a success message. Checkout and the other adapters are untouched.

3. Why is checkout(PaymentGateway g) easy to test now?

Answer

A test can pass a fake PaymentGateway that returns a fixed message and records the amount, so no bank SDK and no network are needed.

4. When would a class adapter be acceptable?

Answer

When the adaptee is a non-final class you fully control, you need to override one of its methods, and you will only ever adapt that one class. Even then, an object adapter is usually just as easy.

5. List<Integer> l = Arrays.asList(3, 1, 2); Collections.sort(l); Does it work? What about l.remove(0)?

Answer

Sorting works: it only uses set, which the fixed-size list supports. remove(0) throws UnsupportedOperationException, because it would change the size.

Quick quiz

interface Sms { void send(String phone, String text); }

// The SMS company's SDK (can't be edited):
class TextLineSdk {
    public int push(String text, String to) { ... }
}

// You need an Sms. Which class do you write?
  • A. class A extends Sms
  • B. class A implements TextLineSdk
  • C. class A implements Sms { TextLineSdk sdk; }
  • D. Edit TextLineSdk to implement Sms
Answer

C. An object adapter implements the target (Sms) and holds the adaptee; send() calls sdk.push(text, phone). A and B don't compile (you implements an interface and extends a class), and D isn't allowed: it's not your code.

Interview questions

  1. What is the Adapter pattern? A structural pattern that converts the interface of a class into another interface clients expect, so incompatible classes can work together.
  2. Name the participants. Target, adaptee, adapter, client.
  3. Object adapter vs class adapter? Object adapter holds the adaptee and delegates (composition; works with final classes and subclasses). Class adapter extends the adaptee and implements the target (inheritance; limited by single inheritance and final classes).
  4. When do you use it? Integrating third-party SDKs, legacy code, or any class whose interface you can't or shouldn't change.
  5. Adapter vs Decorator? Adapter changes the interface; Decorator keeps the interface and adds behaviour.
  6. Adapter vs Facade? Adapter makes one existing interface fit an expected one; Facade defines a new, simpler interface over a whole subsystem.
  7. Examples in the JDK? Arrays.asList, InputStreamReader, Collections.list(Enumeration).
  8. What is a two-way adapter? An adapter that implements both interfaces so old and new clients can use the same object.
  9. What should an adapter not do? Contain business rules; it should only translate (names, argument order, units, types, errors).
  10. How does Adapter help testing? Clients depend on your own interface, so tests can pass fakes.

Glossary

Term Meaning, with an example
Structural patterns Patterns about how classes and objects are connected: Adapter, Decorator, Proxy, Facade, Bridge, Composite, Flyweight
Adapter pattern Converts one interface into the interface a client expects. BankSdkAdapter
Target interface The interface the client expects. PaymentGateway
Adaptee The existing class with the wrong interface. BankSdk
Adapter The class that implements the target and translates calls to the adaptee
Client Code that uses only the target. checkout()
Wrapper An object that holds another object and changes how you use it; another name for an adapter (and a decorator)
Delegation / forwarding Passing a call on to another object (episode 11). sdk.transfer(...)
Object adapter Adapter that holds the adaptee in a field (composition)
Class adapter Adapter that extends the adaptee class (inheritance)
Final class A class that can't be extended. final class BankSdk
SDK Software development kit: ready-made code a company gives you to use its service
Third-party code Code written and owned by another company; you use it but don't edit it
Legacy code / legacy integration Old code that still runs the business / connecting it to new code without rewriting it
Two-way adapter One object that implements both the old and the new interface. CartBridge
UPI ID / VPA A payment address like asha@upi; VPA = virtual payment address
Paise One hundredth of a rupee; Rs 240 = 24000 paise
instanceof Checks an object's type at runtime (episode 9)
Incompatible types Compile error when a value's type can't be used where another type is expected
Arrays.asList Returns a fixed-size List view backed by an array
Write-through A change through the view changes the underlying data. list.set(0, ...) changed menu[0]
UnsupportedOperationException Thrown when an object can't perform an optional operation. add on Arrays.asList
Fake (test double) A simple stand-in implementation used in tests (episode 53)
Open-Closed Principle Add behaviour without editing existing code (episode 13)
Programming to an interface Depending on an interface, not a concrete class (episode 7)
Composition over inheritance Prefer holding objects to extending classes (episode 11)

Summary

  • An adapter converts an existing class's interface (the adaptee) into the interface the client expects (the target), without editing either side.
  • Put every translation (names, argument order, units, result types, errors) in one place: the adapter. Scattered conversions cause bugs like paying Rs 24000 instead of Rs 240.
  • Prefer the object adapter (has-a) to the class adapter (is-a), which breaks on final classes.
  • Arrays.asList is a JDK adapter: a fixed-size, write-through List view of an array; add throws UnsupportedOperationException.
  • Wrap every third-party SDK and legacy API behind your own interface; use a two-way adapter when old and new code share an object.
  • Adapter changes the interface; Decorator adds behaviour; Facade hides complexity.

Next episode: The Decorator pattern.