← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Structural Patterns

🔌Adapter Pattern

Convert the interface of a class into another interface clients expect.

📌 Key IdeaLets classes work together that couldn't because of incompatible APIs. Implement your Target interface; internally delegate to Adaptee (legacy, SDK). Class adapter (inheritance) or object adapter (composition — preferred).
🖼

Visual

🔌 Wrap legacy / third-party API
  Target API          Adaptee (vendor SDK)
  ┌──────────┐        ┌─────────────────┐
  │ Payment  │◀───────│ StripeAdapter   │
  │ .pay()   │ wraps  │ stripe.charge() │
  └──────────┘        └─────────────────┘

Client depends only on Target; adapter translates calls.

✅

When to Use

  • Integrating legacy or vendor code whose API doesn't match your domain.
  • You want one stable interface (PaymentProcessor) with many backends.
  • Gradual migration — old module behind adapter until replaced.
🚫

When NOT to Use

  • You control both sides — change the API instead of wrapping.
  • You're really sharing behaviour across subclasses — might be Decorator.
🚨

Anti-Pattern (What NOT to Do)

Client sprinkled with vendor typesBadjava
void checkout(Cart c) {
    com.stripe.model.Charge ch = Stripe.api(...); // leaks everywhere
Testing and swapping gateways becomes painful.
✅

The Right Way

Adapter implements your portGoodjava
interface PaymentPort { Result charge(Money m); }

class StripePayment implements PaymentPort {
    public Result charge(Money m) {
        return map(stripeClient.charge(toStripe(m)));
    }
}
Domain stays clean; Stripe types trapped in adapter.
⚖️

Pros & Cons

👍 Pros
  • Single Responsibility — translation isolated.
  • Open/Closed — new gateways = new adapters.
  • Improves testability — mock PaymentPort.
👎 Cons
  • Extra indirection and mapping code.
  • Wrong abstraction leaks if adaptee keeps bubbling up.
🔀

Common Confusions Cleared Up

Adapter vs Decorator

Adapter changes interface to something clients already expect. Decorator keeps the same interface but adds behaviour (layers). Adapter fixes mismatch; decorator enhances.

Adapter vs Facade

Adapter maps one interface to another (often 1:1). Facade simplifies a subsystem of many classes behind one broader entry point.

🎤

Interview Q&A

🔮

Likely Follow-up Questions

  • Two-way adapter (maps A↔B) — when needed?
  • How does this relate to ports and adapters / hexagonal architecture?
🧾

Quick Cheat Sheet

IntentMake incompatible interfaces work together.
PreferObject adapter (composition).
vs DecoratorChange API vs same API + behaviour.
Interview hitLegacy SDK behind your interface.
🔗

Related Topics