Adapter
Lets two incompatible interfaces work together, by wrapping one so it looks like the other.
Why it matters
You often need a library or old system whose interface doesn't match the one your code expects, and you can't (or shouldn't) change either side.
The idea
Your code expects pay(amount_in_pounds), but a third-party SDK offers make_payment(pence, currency). An adapter wraps the SDK and translates the calls, so your code doesn't change.
A UK-to-EU travel plug adapter.
A plug adapter only changes the shape. Software adapters often also convert data (units, formats, errors), and a careless conversion can hide real problems.
How it works
- Write down the interface your code expects: pay(pounds) returning True or False.
- Write down what the other system offers: make_payment(pence, currency) returning 'OK' or an error code.
- Create an adapter class that implements your interface and holds the other system.
- In each method, convert the inputs (pounds → pence), call the other system, and convert the outputs (codes → True/False, or proper exceptions).
Example
Wrapping an old XML-based bank service so it fits your new PaymentGateway interface.
Key points
- Use it to plug in third-party or legacy code without changing your own interface.
- Prefer wrapping an object (object adapter) over inheriting from it (class adapter).
- Keeps vendor-specific code in one place, so switching vendors is easy.
Common mistakes
- Letting the third-party's types leak through the adapter into business code.
- Losing error details during the conversion.
Not true: An adapter should hand the third party's own types back to the code that calls it.
In fact: The business code would then depend on the vendor after all. An adapter converts everything into your own types, so the vendor's code stays in one place.
In the interview
Adapter wraps an incompatible class so that it matches the interface my code expects: for example, making an old bank SDK fit our PaymentGateway interface. Business code doesn't change, and vendors can be swapped.
Part of Unit 6: Design patterns in the free System Design course.