What is the Adapter pattern?

SOLID & Design Patterns Patterns Basic 1–2 Yrs2–3 Yrs Architecture 1 min read

Quick Answer

Adapter converts one interface into another that a client expects. You have a third-party library (or legacy class) with the wrong shape, and you wrap it in a class that implements your interface and translates the calls. It's how you keep an external dependency from spreading through your codebase.

Adapter is a translation layer. I've got some external SDK or a legacy class whose API doesn't match what my code wants, so I write a class that implements my interface and internally calls the external thing, converting between the two shapes. So my domain only ever sees IPaymentGateway, and the fact that it's Stripe underneath is contained in one adapter class. If we switch providers, that's one new class, nothing else changes. At the architecture level this is the anti-corruption layer idea.

  • class StripeGatewayAdapter : IPaymentGateway wraps the Stripe SDK and maps your Charge(request) onto Stripe's API and its response back to your model.
  • Your domain depends only on IPaymentGateway; swapping to PayPal is a new adapter.
  • At a larger scale this is the anti-corruption layer in DDD — a boundary that translates another system's model into yours.
  • Adapter vs Facade: adapter changes an interface to match an expectation; facade simplifies a complex subsystem behind one entry point.