Adapter pattern
easy 50 minThe Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.
Chapter mnemonic
Structural design patterns
Ancient books conceal dragons folded from paper.
Video lesson · Chapter 1 of 5
One client, two languages
Adapter
1:03Reel
More reels
One idea each, a minute or less.
Adapter vs facade
0:34Reel
Theory
Read or listen first. About 2 min.
What it is
The Adapter pattern is a structural design pattern. An adapter implements the interface that a client expects (the target) and does the work with an existing object that has another interface (the adaptee).
It is also called a wrapper, a name it shares with Decorator and Proxy. What makes it an adapter is that the interface changes.
It comes in two classic forms: the object adapter holds the adaptee, the class adapter inherits from it.
Why it exists
Useful code often has the wrong shape: it was written by others, earlier, for another program. Rewriting it throws away its tested years. Calling it directly spreads its words through your program.
With an adapter, one class knows both languages. A new version, a new vendor or a fake for tests is one new class.
It also makes you write down what you really need. The target is a list of promises, and the gap between the promises and the library is a list of work.
A short history
1994
The book Design Patterns appears on 31 October and lists Adapter among its structural patterns, with Wrapper as its other name.
1997
JDK 1.1 is released on 19 February with JDBC: one interface for programs, and a driver for each database behind it.
2003
Eric Evans publishes Domain-Driven Design. Its anti-corruption layer applies the idea to whole systems.
2010
PEP 3333 updates the Python interface between web servers and web programs, WSGI. Servers with another interface reach WSGI programs through adapters.
2017
PEP 544 proposes protocols for Python: a class fits an interface by its shape, without naming it. Some adapters become unnecessary.
Words to know
- Target
- The interface that the client expects.
- Adaptee
- The existing class whose interface does not match.
- Adapter
- Implements the target with the help of the adaptee.
- Object adapter
- Holds the adaptee as a field.
- Class adapter
- Inherits from the adaptee.
- Two-way adapter
- Offers both interfaces.
- Pluggable adapter
- Gets the differences as functions.
- Gap list
- The differences between your promises and a library, row by row.
- Contract test
- One suite that every implementation of an interface must pass.
- Outcome unknown
- No answer arrived. The work may have been done.
- Anti-corruption layer
- A border of adapters and translators that keeps a foreign model out.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Client calls the target. In its own words and units
Understand it
Start here
Two things that work, and do not fit
You have code that works. Somebody else has code that works. Together they do not, because one asks for play(file, seconds) and the other offers load, seek and run. The Adapter pattern is the small piece in the middle that makes them fit, without opening either of them.
The fire engine knows one thing: claws in, water out. Everything else is the business of the ring.
Four parts
Target
The interface the client wants:
MediaPlayer,PaymentGateway. Written in the words of your own program.Client
Calls the target and knows nothing else:
AudioPlayer, a checkout.Adaptee
The existing class with another interface: a library, a vendor, old code. You can not or will not change it.
Adapter
Implements the target, holds the adaptee, translates every call and every answer.
Why
What goes wrong without it
The first version calls the foreign class directly. It works on the first day. Then the same three lines of translation appear in a second place, and one copy forgets that the library wants milliseconds.
class VlcEngine: def play_vlc(self, path, offset_ms): return f"{path} from {offset_ms / 1000:.2f}s"class PlayButton: def __init__(self, engine): self.engine = engine def press(self, path, seconds): return self.engine.play_vlc(path, seconds * 1000)class ResumeButton: # written three months later def __init__(self, engine): self.engine = engine def press(self, path, seconds): return self.engine.play_vlc(path, seconds) # seconds, not millisecondsengine = VlcEngine()print(PlayButton(engine).press("movie.vlc", 90))print(ResumeButton(engine).press("movie.vlc", 90)) # almost at the beginningThe design that hurts
1/3One button, one library
The button multiplies by 1000 itself. Nobody complains.
uses
offset_ms, 415) inside classes that have nothing to do with that library.One adapter
- One place knows both languages
- Your code speaks its own words only
- A new version means one file
- Tests use a small fake of the target
Foreign calls everywhere
- Unit conversion is copied
- Error codes of the vendor travel through your code
- A new version of the library means a search through the whole program
- Tests need the real library
The idea
Write the interface you wish you had
Begin at the client. Ask: if the library did not exist, how would I want to call it? Write that down as an interface. Then let one class bridge the difference. The order matters: an interface copied from the library is not a target, it is the library again.
The Adapter pattern in general
1/4The client and its wish
Target belongs to the client. It is named after what the client needs.
usesimplementshas (lives on)
One call, translated twice
What an adapter translates
| Difference | Client says | Adaptee wants | If you forget it |
|---|---|---|---|
| Name | play | play_vlc | It does not compile |
| Order of calls | one call | load, seek, run | It plays the previous file |
| Unit | seconds | milliseconds | Wrong place, no error |
| Type | Money | text "12.50" | Rounding, or 100 times too much |
| Error | exception | number 415 | A failure looks like success |
| Nothing found | empty list | null | Crash, far away from the cause |
| Time | UTC | local time | One hour wrong twice a year |
Forms
Object adapter and class adapter
There are two classic ways to build the piece in the middle. The object adapter holds an adaptee. The class adapter inherits from it.
Two ways to adapt
1/2Object adapter
Has an engine. Works with every subclass of the engine, and you choose the engine when you build the adapter.
implementshas (lives on)extends (is a)
| Object adapter | Class adapter | |
|---|---|---|
| Relation | has an adaptee | is an adaptee |
| Adapts subclasses too | Yes, pass any of them in | No, one class per adaptee class |
| Override adaptee behaviour | Only through a subclass of the adaptee | Directly |
| Objects | Two | One |
| Foreign methods visible | No | Yes, in C++ only if you inherit publicly |
| Final or sealed adaptee | Works | Impossible |
| Coupling | To the public methods | Also to protected parts and to the constructor |
Other forms you will meet
Two-way adapter
Implements both interfaces, so each side can treat it as one of its own. Useful while two systems run side by side.
Pluggable adapter
The differences are passed in as functions:
FunctionAdapter(play=engine.play_vlc). No class per adaptee.Function adapter
A function that wraps a function.
util.promisifyin Node.js turns a callback function into one that returns a promise.Default adapter
A base class with empty methods, so that a listener overrides only what it needs. It shares the name, not the purpose.
Another picture
The travel plug, and what it does not do
Sarah lands in Paris with a charger from the US. Flat blades do not enter round holes. A travel plug has US slots on one side and round pins on the other: nobody rewires the hotel, nobody cuts the charger. But most travel plugs change only the shape. In the US the socket gives 120 V, in France 230 V. Sarah's phone charger accepts 100 to 240 V, so it works. A hair dryer built for 120 V only would burn.
Choosing
When to use it and when not
Use it when
- You want an existing class whose interface does not match
- A third-party library or a vendor may be replaced
- Legacy code must work with new code
- Several classes should look the same to one client
- You want to test without the real thing
Leave it when
- The interfaces already match
- You own both sides and can simply rename
- The mismatch is too large: then it is a new component, not an adapter
- Each adapter wraps another adapter
- A very hot inner loop, where you measured that the extra call matters
Do I need an adapter?
The vendor's Customer object has 40 fields and we use it in 25 files. The vendor announces version 2. What do you do?
BreaksEdit the 25 files
- How
- Search and replace the new names.
- Limit
- The next version costs the same again. Two versions can not run side by side.
- Choose when
- Never, unless the vendor is about to disappear anyway.
WorksWrap the vendor class one to one
- How
CustomerWrapperwith the same 40 methods.- Limit
- All names and units of the vendor are still in your code. Version 2 changes the wrapper's interface too.
- Choose when
- A short stop on the way, when there is no time today.
StrongOur own Customer with the 6 fields we need, filled by an adapter
- How
CustomerSource.find(id)returns our type. One adapter for version 1, one for version 2.- Limit
- You must decide what you really need, and map it.
- Choose when
- When a foreign model has spread. It also lets you run both versions and compare.
Neighbours
Adapter and the other wrappers
| Pattern | Interface | Purpose | Wraps |
|---|---|---|---|
| Adapter | Changed to the one expected | Make an existing thing fit | One object, sometimes a few |
| Decorator | Same | Add behaviour | One object, in layers |
| Proxy | Same | Control access | One object |
| Facade | New and simpler | Make many things easy | A subsystem |
| Bridge | Two, designed together | Let two sides grow apart | Planned from the start |
| Strategy | One, many versions | Choose an algorithm | Nothing |
Trade-offs
What you gain and what you pay
Reuse
The existing class is used as it is, with its tests and its years of fixed bugs.
Flexible
Swap one adapter for another when the program starts, or per customer.
Open and closed
A new library is a new class plus one line of wiring. The client stays closed.
One more layer
One more call to read, and one more place to look for a bug. A stack trace gets one line longer.
Lowest common part
If the target offers only what all adaptees can do, special features are lost. If it offers more, some adapters must refuse.
Summary
The whole topic in one minute.
Write the interface the client wants. One adapter per foreign class implements it and holds that class. Only adapters see both sides.
Translate names, order, units, types, errors and empty results. Refuse aloud, with your own error. Keep business rules out.
In production: no and silence are different errors, keys come from the caller, retries wrap the adapter, and one contract suite runs against the fake, the adapter and the vendor.
- An adapter makes an existing class fit the interface that its client expects. Neither side changes.
- Design the target from the client's needs. A copy of the library's interface is not a target.
- Names are the easy part. Translate order, units, types, errors, empty results and time too.
- Prefer the object adapter. A class adapter only to override something inside.
- Keep decisions out of it: an adapter translates, it does not run business rules.
- Run one contract test against every adapter.