Adapter
An adapter sits in front of a type you cannot change and presents the interface your code already uses. It translates calls and data so two incompatible APIs can work together.
Detailed Explanation
You have a PaymentGateway interface. The vendor shipped StripeClient.chargeCents. You do not own the vendor class. An adapter implements PaymentGateway and forwards to StripeClient. Your application keeps talking to PaymentGateway. When the vendor changes, you change one class.
Class adapters (multiple inheritance) are rare in Java. Object adapters (a field holding the adaptee) are the norm. InputStreamReader adapts a byte stream to a Reader. Arrays.asList adapts an array to a List (with a fixed size). Collections.list adapts an Enumeration to a List.
Adapter is not decorator. A decorator implements the same interface as the wrappee and adds behaviour. An adapter implements a different interface. Adapter is not facade: a facade simplifies a subsystem; an adapter maps one contract onto another.
You reach for an adapter at a boundary: third-party SDK, legacy module, JDK type that almost fits. You do not wrap your own new code in an adapter; you just implement the interface.
The cost is an extra type and a translation that can lose information (exceptions, units, nulls). Document the mapping. Test the adapter with a fake adaptee. Keep it thin: no business rules. If the adapter grows rules, those rules belong in the application, not in the translation layer.
Two-way adapters exist when both sides must call each other. They are harder; prefer one direction.
Put adapters at the edge of the application. A package named stripe or legacy that only other adapters import is a good sign. If domain code imports StripeClient, the adapter has leaked. Tests then need Stripe. Keep the domain talking to PaymentGateway only, and the adapter is doing its job even when it is ten lines long.
Code Examples
interface Mailer {
void send(String to, String body);
}
class LegacySmtp {
void post(String rcpt, String text) {
System.out.println(rcpt + ":" + text);
}
}
class SmtpMailer implements Mailer {
private final LegacySmtp smtp;
SmtpMailer(LegacySmtp smtp) {
this.smtp = smtp;
}
@Override
public void send(String to, String body) {
smtp.post(to, body); // translate the call
}
public static void main(String[] args) {
Mailer mailer = new SmtpMailer(new LegacySmtp());
mailer.send("a@b.com", "hi"); // prints: a@b.com:hi
}
}Common Gotchas
Do not hide unit changes silently
paise vs rupees in an adapter is a money bug.
`Arrays.asList` is an adapter, not a copy
`set` writes through; `add` throws.
Fat adapters that contain business rules become a second domain layer
Fat adapters that contain business rules become a second domain layer