Skip to content

Design Patterns

Adapter

Calling through the adapter costs O(1) extra work — just one more function call.

The idea, in plain English

An adapter works like a travel plug adapter. Your charger has one shape of plug, and the wall socket has another. You don't rebuild either one — you plug a small adapter in between so they fit. In code, an adapter sits between two mismatched pieces and translates one into the other.

How it works

  1. 1You start with an existing object whose methods don't match what your code expects.
  2. 2You wrap it in an adapter object that offers the method name your code wants.
  3. 3Inside, the adapter calls the old object's real method and returns the result. All the translation happens in one place.

When you'd use it

Use this when you're plugging in an old class, a third-party library, or someone else's code that almost fits, but not quite, and you don't want to rewrite it.

Common beginner mistakes

  • Don't try to change the original class instead of wrapping it. Sometimes you can't — it's someone else's code.
  • Don't put extra logic inside the adapter beyond translation. That makes it confusing to follow.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Old printer: Hello

Not sure this is the right topic? See the learning paths → or where this leads →