Explain the Adapter pattern.
Topic: design-patterns, Structural Patterns. Level: Basic.
Answer
Adapter converts the interface of a class into another interface the client expects, letting incompatible interfaces work together — like a plug adapter. Use it to integrate a third-party/legacy class whose API you can't change into your codebase's expected interface. It wraps the adaptee and translates calls. (In DDD, an anti-corruption layer is an adapter at a service boundary.)
```java
// Target interface our app expects
interface PaymentGateway { boolean pay(long cents); }
// Incompatible third-party class we can't modify
class StripeApi { void charge(double dollars, String cur) { /* ... */ } }
// Adapter translates our interface -> the third-party API
class StripeAdapter implements PaymentGateway {
private final StripeApi stripe = new StripeApi();
public boolean pay(long cents) {
stripe.charge(cents / 100.0, "USD"); // translate call/units
return true;
}
}
PaymentGateway gw = new StripeAdapter(); // app code stays gateway-agnostic
```