CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Adapter

Convert one interface into another.

Think of a travel plug. The wall socket in another country has a different shape, and the laptop charger cannot change. The plug adapter sits in between, and it changes only the shape.

GoF's intent for Adapter is to make one class look like the interface a client expects, so two classes with mismatched interfaces can still cooperate. GoF suggests it when an existing class is useful but its methods do not line up with what you need, or when you are building a reusable class that must work with unrelated classes whose interfaces cannot be known in advance.

Here is a case from the payment exercise in Level 2. The booking code wants a simple Payments interface. A vendor library, which nobody on the team can edit, offers a differently shaped method.

interface Payments { boolean charge(String user, long rupees); }

class VendorGateway {            // third-party code, cannot be changed
    String chargeCardV2(String account, long paise, String currency) {
        return paise > 0 ? "OK-" + account : "FAIL";
    }
}

class VendorPayments implements Payments {     // the adapter
    private final VendorGateway g;
    VendorPayments(VendorGateway g) { this.g = g; }

    public boolean charge(String user, long rupees) {
        return g.chargeCardV2(user, rupees * 100, "INR").startsWith("OK");
    }
}

The adapter turns rupees into paise, supplies the currency code, and turns the text result into a boolean. charge("asha", 500) returns true. charge("asha", 0) sends 0 paise and returns false. The rest of the program sees only Payments. If the vendor changes or a second vendor is added, only the adapter changes. This is the dependency inversion principle (Level 2, module 5) in practice: the interface belongs to our code, and the vendor's class is a detail behind it.

GoF names four roles. The Target is the interface the client wants (Payments). The Client uses the target. The Adaptee is the existing class (VendorGateway). The Adapter makes the adaptee fit the target.

Adapter pattern

The Adapter pattern wraps an existing class in a new class that offers the interface a client expects, translating calls and results between the two.

Example: VendorPayments, which presents the vendor gateway as Payments.

Check yourself: 1. What does the adapter change in the call to the vendor? 2. Which class is the adaptee? 3. If a second vendor is added, what must be written?