Adapter Pattern
Wrap a class whose interface does not fit so that the code you already have can call it without changing either side.
Overview
The problem it solves The code you already have calls one interface, and a class you need offers a different one. You cannot change the class (it is a library, a vendor SDK or old code with many callers), and you do not want to rewrite every caller. An adapter sits between them. It implements the interface your code expects and translates each call into the calls the other class understands.
The pattern is one of the seven structural patterns in the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). The book calls the interface your code wants the Target, the class you are stuck with the Adaptee, and the translator the Adapter.
Three things change inside the adapter and nowhere else: method names, the shape of arguments and results, and small protocol differences such as units, error codes or exceptions. Business rules do not belong there. If the adapter starts deciding things, it has become something else.
Interview questions
- What are the participants of the Adapter pattern, and who depends on whom?
- Show the smell an adapter removes, and the fix.
- When is an adapter the wrong choice?
- How do you test an adapter?
- What is a two-way adapter, and when would you need one?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio