Adapter Pattern
Learn how to make two classes with different interfaces work together without changing either, using a payment gateway example, and how the JDK already uses adapters.
When you travel to another country, your phone charger often does not fit the wall socket. The plug is the wrong shape. You have two choices: change the charger, or change the wall. Both are impossible. So you buy a small travel adapter. One side fits the foreign socket, the other side fits your charger. Neither the charger nor the wall changes, and yet they work together.
The Adapter pattern does exactly this in code. It is the first of the structural patterns, the group of patterns about how classes and objects are combined into larger structures. An adapter sits between two pieces of code whose interfaces do not match, and translates between them.
01The problem: the interfaces do not match
Your shop's checkout code works with a clean interface that you designed:
public interface PaymentGateway {
PaymentResult pay(long amountInCents, String customerId);
}The CheckoutService calls gateway.pay(...), and several payment providers already implement this interface. Now the business signs a contract with an old bank, and the bank supplies a Java library with its own class:
public class LegacyBankApi {
// returns 0 on success, or a positive error code
public int makeTransfer(String accountCode, int amountInRupees, boolean urgent) {
/* talks to the bank's old system */
return 0;
}
}Compare the two. They do the same job, but nothing matches:
| Our interface | The bank's class | |
|---|---|---|
| Method name | pay | makeTransfer |
| Amount | long, in cents | int, in whole rupees |
| Customer | customerId | accountCode |
| Extra argument | none | an urgent flag |
| Result | a PaymentResult object | an int code, 0 means success |
You cannot edit the bank's class, because it is in a library that belongs to someone else. You do not want to edit CheckoutService and every other caller, because that would spread the bank's strange style through your whole code base. What you want is to keep your interface and let something translate.
Loading the rest of the lesson…