AlgoViz

Adapter pattern

easy 50 min

The 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

0:00 / 4:39

Adapter

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1994

    The book Design Patterns appears on 31 October and lists Adapter among its structural patterns, with Wrapper as its other name.

  2. 1997

    JDK 1.1 is released on 19 February with JDBC: one interface for programs, and a driver for each database behind it.

  3. 2003

    Eric Evans publishes Domain-Driven Design. Its anti-corruption layer applies the idea to whole systems.

  4. 2010

    PEP 3333 updates the Python interface between web servers and web programs, WSGI. Servers with another interface reach WSGI programs through adapters.

  5. 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.

Step 1 of 3

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 hose coupling

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.

Python
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 beginning
Run it. Both buttons are asked for second 90. One of them starts at 0.09 seconds.
Edit and run it in your browser

The design that hurts

PlayButton+ press(): x 1000VlcEngine+ playVlc(path, ms)

1/3One button, one library

The button multiplies by 1000 itself. Nobody complains.

uses

The smell: the vocabulary of a library (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

Client+ doWork()«interface»Target+ request()

1/4The client and its wish

Target belongs to the client. It is named after what the client needs.

usesimplementshas (lives on)

The open diamond: the adapter has the adaptee, it did not necessarily create it. Both can exist without the other.

One call, translated twice

On the way in: names, order and units. On the way out: the answer, and the error. The second half is often forgotten.

What an adapter translates

DifferenceClient saysAdaptee wantsIf you forget it
Nameplayplay_vlcIt does not compile
Order of callsone callload, seek, runIt plays the previous file
UnitsecondsmillisecondsWrong place, no error
TypeMoneytext "12.50"Rounding, or 100 times too much
Errorexceptionnumber 415A failure looks like success
Nothing foundempty listnullCrash, far away from the cause
TimeUTClocal timeOne hour wrong twice a year
The compiler finds the first row only. The others need a person and a test.

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

has«interface»MediaPlayer+ play()VlcAdapter- engine+ play()VlcEngine+ playVlc()

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)

Java, C#, TypeScript and JavaScript allow one base class, so a class adapter works only if the target is an interface. C++ and Python allow several.
Object adapterClass adapter
Relationhas an adapteeis an adaptee
Adapts subclasses tooYes, pass any of them inNo, one class per adaptee class
Override adaptee behaviourOnly through a subclass of the adapteeDirectly
ObjectsTwoOne
Foreign methods visibleNoYes, in C++ only if you inherit publicly
Final or sealed adapteeWorksImpossible
CouplingTo the public methodsAlso to protected parts and to the constructor
Choose the object adapter unless you must override something inside the adaptee. Favour composition is the general rule behind it.

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.promisify in 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 question in the middle is the important one. If the other side can not do what you promise, no wrapper will hide it.

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
CustomerWrapper with 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

PatternInterfacePurposeWraps
AdapterChanged to the one expectedMake an existing thing fitOne object, sometimes a few
DecoratorSameAdd behaviourOne object, in layers
ProxySameControl accessOne object
FacadeNew and simplerMake many things easyA subsystem
BridgeTwo, designed togetherLet two sides grow apartPlanned from the start
StrategyOne, many versionsChoose an algorithmNothing
Ask two questions: did the interface change, and was it planned? Changed and not planned is an adapter.

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.

Sources