Adapter: The Interpreter Between Two Strangers

When the hub's routines are written in three brands' words (setPower, release, startStream), every new brand edits every routine; an adapter is a small class that keeps the hub's own promise and passes each call on in the brand's words, so the hub never learns a brand's language.

Apprentice · OOP · Updated

By

After this lesson you can

  • Write an adapter that makes a class you can't change keep the interface your code expects
  • Spot the smells that point to Adapter: another library's method names and types spread through your own code

Key takeaways

  • The smell: another company's method names, and its types, spread through your own code's routines.
  • The cause: your code speaks each outside library's language itself, so it changes whenever they do, or a new one arrives.
  • The fix: one small class per brand that keeps your interface and translates each call into the brand's words. Your code only ever sees your interface.
  • In today's languages an adapter can be a single object made from two or three small functions; it's the same idea.

Before this: Meet the Smart-Home Hub, which plans the hub's own Light, Lock and Speaker promises, and delegation (one object handing a job to another it holds).

Maya's Bolt lock is on the front door, and the Tuneo speaker is in the kitchen. Now "good morning" should turn on the kitchen light, unlock the front door and start the news, and a new routine, "leaving home", should do the opposite. Someone wired them in the quick way, straight into the hub. It works. This lesson is about why it won't keep working, and the fix teams found for it, called an adapter.

The symptom: the hub speaks three languages

Here is the hub with both routines, written in each brand's own words:

Hub hub = new Hub(new LumoLight("kitchen"), new BoltLock("front door"), new TuneoSpeaker("kitchen"));
hub.GoodMorning();
hub.LeaveHome();

// The hub, the quick way: its routines use each brand's own words.
class Hub
{
    private const string News = "https://tuneo.example/news";
    private readonly LumoLight light;
    private readonly BoltLock door;
    private readonly TuneoSpeaker speaker;

    public Hub(LumoLight light, BoltLock door, TuneoSpeaker speaker)
    {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    public void GoodMorning()
    {
        Console.WriteLine("Good morning:");
        light.SetPower(true);
        door.Release();
        speaker.StartStream(News);
    }

    public void LeaveHome()
    {
        Console.WriteLine("Leaving home:");
        light.SetPower(false);
        door.Engage();
        speaker.Halt();
    }
}

// The brands' own code: the hub can use it, but can't change it.
class LumoLight { private readonly string room; public LumoLight(string room) { this.room = room; } public void SetPower(bool on) => Console.WriteLine(quot;Lumo [{room}]: power {(on ? "on" : "off")}"); }
class BoltLock { private readonly string door; public BoltLock(string door) { this.door = door; } public void Engage() => Console.WriteLine(quot;Bolt [{door}]: ENGAGED"); public void Release() => Console.WriteLine(quot;Bolt [{door}]: RELEASED"); }
class TuneoSpeaker { private readonly string room; public TuneoSpeaker(string room) { this.room = room; } public void StartStream(string url) => Console.WriteLine(quot;Tuneo [{room}]: streaming {url}"); public void Halt() => Console.WriteLine(quot;Tuneo [{room}]: halted"); }
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
// The brands' own code: the hub can use it, but can't change it.
class LumoLight { private final String room; LumoLight(String room) { this.room = room; } void setPower(boolean on) { IO.println("Lumo [" + room + "]: power " + (on ? "on" : "off")); } }
class BoltLock { private final String door; BoltLock(String door) { this.door = door; } void engage() { IO.println("Bolt [" + door + "]: ENGAGED"); } void release() { IO.println("Bolt [" + door + "]: RELEASED"); } }
class TuneoSpeaker { private final String room; TuneoSpeaker(String room) { this.room = room; } void startStream(String url) { IO.println("Tuneo [" + room + "]: streaming " + url); } void halt() { IO.println("Tuneo [" + room + "]: halted"); } }

// The hub, the quick way: its routines use each brand's own words.
class Hub {
    static final String NEWS = "https://tuneo.example/news";
    private final LumoLight light;
    private final BoltLock door;
    private final TuneoSpeaker speaker;

    Hub(LumoLight light, BoltLock door, TuneoSpeaker speaker) {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    void goodMorning() {
        IO.println("Good morning:");
        light.setPower(true);
        door.release();
        speaker.startStream(NEWS);
    }

    void leaveHome() {
        IO.println("Leaving home:");
        light.setPower(false);
        door.engage();
        speaker.halt();
    }
}

void main() {
    Hub hub = new Hub(new LumoLight("kitchen"), new BoltLock("front door"), new TuneoSpeaker("kitchen"));
    hub.goodMorning();
    hub.leaveHome();
}
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
NEWS = "https://tuneo.example/news"


# The brands' own code: the hub can use it, but can't change it.
class LumoLight:
    def __init__(self, room): self.room = room
    def set_power(self, on): print(f"Lumo [{self.room}]: power {'on' if on else 'off'}")


class BoltLock:
    def __init__(self, door): self.door = door
    def engage(self): print(f"Bolt [{self.door}]: ENGAGED")
    def release(self): print(f"Bolt [{self.door}]: RELEASED")


class TuneoSpeaker:
    def __init__(self, room): self.room = room
    def start_stream(self, url): print(f"Tuneo [{self.room}]: streaming {url}")
    def halt(self): print(f"Tuneo [{self.room}]: halted")


class Hub:
    """The hub, the quick way: its routines use each brand's own words."""

    def __init__(self, light, door, speaker):
        self.light = light
        self.door = door
        self.speaker = speaker

    def good_morning(self):
        print("Good morning:")
        self.light.set_power(True)
        self.door.release()
        self.speaker.start_stream(NEWS)

    def leave_home(self):
        print("Leaving home:")
        self.light.set_power(False)
        self.door.engage()
        self.speaker.halt()


hub = Hub(LumoLight("kitchen"), BoltLock("front door"), TuneoSpeaker("kitchen"))
hub.good_morning()
hub.leave_home()
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
const NEWS = "https://tuneo.example/news";

// The brands' own code: the hub can use it, but can't change it.
class LumoLight { constructor(room) { this.room = room; } setPower(on) { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { constructor(door) { this.door = door; } engage() { console.log(`Bolt [${this.door}]: ENGAGED`); } release() { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { constructor(room) { this.room = room; } startStream(url) { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt() { console.log(`Tuneo [${this.room}]: halted`); } }

// The hub, the quick way: its routines use each brand's own words.
class Hub {
  constructor(light, door, speaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning() {
    console.log("Good morning:");
    this.light.setPower(true);
    this.door.release();
    this.speaker.startStream(NEWS);
  }

  leaveHome() {
    console.log("Leaving home:");
    this.light.setPower(false);
    this.door.engage();
    this.speaker.halt();
  }
}

const hub = new Hub(new LumoLight("kitchen"), new BoltLock("front door"), new TuneoSpeaker("kitchen"));
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
const NEWS = "https://tuneo.example/news";

// The brands' own code: the hub can use it, but can't change it.
class LumoLight { private readonly room: string; constructor(room: string) { this.room = room; } setPower(on: boolean): void { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { private readonly door: string; constructor(door: string) { this.door = door; } engage(): void { console.log(`Bolt [${this.door}]: ENGAGED`); } release(): void { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { private readonly room: string; constructor(room: string) { this.room = room; } startStream(url: string): void { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt(): void { console.log(`Tuneo [${this.room}]: halted`); } }

// The hub, the quick way: its routines use each brand's own words.
class Hub {
  private readonly light: LumoLight;
  private readonly door: BoltLock;
  private readonly speaker: TuneoSpeaker;

  constructor(light: LumoLight, door: BoltLock, speaker: TuneoSpeaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning(): void {
    console.log("Good morning:");
    this.light.setPower(true);
    this.door.release();
    this.speaker.startStream(NEWS);
  }

  leaveHome(): void {
    console.log("Leaving home:");
    this.light.setPower(false);
    this.door.engage();
    this.speaker.halt();
  }
}

const hub = new Hub(new LumoLight("kitchen"), new BoltLock("front door"), new TuneoSpeaker("kitchen"));
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted

Every line of it works. Now read the hub's routines as if you'd never heard of the three brands: setPower, release, engage, startStream, halt. The hub's own code is written in other companies' words, and in C#, Java and TypeScript its constructor even names their classes. The wall panel's buttons and the voice control are about to be written the same way.

Then the next requirement arrives. Sam wants a different speaker in the bedroom, from another brand, with its own words for "play". Every routine that touches a speaker has to learn them.

  • The symptom: another company's method names, and its class names, spread through your own code's routines.
  • The cause: the hub speaks each brand's language itself. So each brand's way of doing things is copied into every place the hub uses it, and every new brand is an edit in all of them.

What would you try?

Add on() and off() to Lumo's class. It isn't ours. It came in Lumo's library, and the next update from Lumo puts their code back the way it was.

Make a subclass of each brand's class that adds the hub's method names. Sometimes that works. But it only works if the brand lets you: Bolt's class is marked so nothing can extend it (sealed in C#, final in Java), and Lumo's library hands you lights it has already made, which aren't your subclass. And your class is now welded to theirs: when Lumo renames a method, your subclass breaks with it.

A helper, turnOn(device), with an if for each brand inside. The brand words move into one function, which is better. But the if chain grows with every brand, and it's the same smell the Pass 1 factory cured: one decision, made by checking what kind of thing you have.

What we want is something that keeps the hub's promise (on(), off()) on the outside, speaks the brand's words on the inside, and lives at the edge, so neither side has to change.

The fix: an interpreter between two strangers

Two people who don't share a language can still do business, with an interpreter between them. Each one talks in their own language, the interpreter listens to one and says the same thing to the other, and nobody has to learn anything new.

An interpreter at a table between two business people: one asks "Can you start on Monday?" and the interpreter asks the other the same question in Spanish, "¿Puedes empezar el lunes?". Both face the interpreter, and neither has to learn the other's language

In code, the interpreter is an adapter: a small class that keeps the interface your code expects, holds the object that doesn't fit, and passes each call on in that object's words. LumoLightAdapter is a Light; its on() calls Lumo's setPower(true). The hub holds a Light and never learns that Lumo exists:

Adapter's roles: the hub, which only knows Light (on, off), asks on() of the adapter, which keeps the hub's Light promise and says it in Lumo's words, setPower(true), to the Lumo light, which can't be changed. The adapter and the light sit in a fence labeled "what changes: the brands"

Hub hub = new Hub(
    new LumoLightAdapter(new LumoLight("kitchen")),
    new BoltLockAdapter(new BoltLock("front door")),
    new TuneoSpeakerAdapter(new TuneoSpeaker("kitchen")));
hub.GoodMorning();
hub.LeaveHome();

// The hub's own promises.
interface ILight { void On(); void Off(); }
interface ILock { void Lock(); void Unlock(); }
interface ISpeaker { void Play(string station); void Stop(); }

// The hub only knows its own promises now.
class Hub
{
    private const string News = "https://tuneo.example/news";
    private readonly ILight light;
    private readonly ILock door;
    private readonly ISpeaker speaker;

    public Hub(ILight light, ILock door, ISpeaker speaker)
    {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    public void GoodMorning()
    {
        Console.WriteLine("Good morning:");
        light.On();
        door.Unlock();
        speaker.Play(News);
    }

    public void LeaveHome()
    {
        Console.WriteLine("Leaving home:");
        light.Off();
        door.Lock();
        speaker.Stop();
    }
}

// One adapter per brand: the hub's promise outside, the brand's words inside.
class LumoLightAdapter : ILight
{
    private readonly LumoLight lumo;
    public LumoLightAdapter(LumoLight lumo) { this.lumo = lumo; }
    public void On() => lumo.SetPower(true);
    public void Off() => lumo.SetPower(false);
}

class BoltLockAdapter : ILock
{
    private readonly BoltLock bolt;
    public BoltLockAdapter(BoltLock bolt) { this.bolt = bolt; }
    public void Lock() => bolt.Engage();
    public void Unlock() => bolt.Release();
}

class TuneoSpeakerAdapter : ISpeaker
{
    private readonly TuneoSpeaker tuneo;
    public TuneoSpeakerAdapter(TuneoSpeaker tuneo) { this.tuneo = tuneo; }
    public void Play(string station) => tuneo.StartStream(station);
    public void Stop() => tuneo.Halt();
}

// The brands' own code, unchanged.
class LumoLight { private readonly string room; public LumoLight(string room) { this.room = room; } public void SetPower(bool on) => Console.WriteLine(quot;Lumo [{room}]: power {(on ? "on" : "off")}"); }
class BoltLock { private readonly string door; public BoltLock(string door) { this.door = door; } public void Engage() => Console.WriteLine(quot;Bolt [{door}]: ENGAGED"); public void Release() => Console.WriteLine(quot;Bolt [{door}]: RELEASED"); }
class TuneoSpeaker { private readonly string room; public TuneoSpeaker(string room) { this.room = room; } public void StartStream(string url) => Console.WriteLine(quot;Tuneo [{room}]: streaming {url}"); public void Halt() => Console.WriteLine(quot;Tuneo [{room}]: halted"); }
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
// The hub's own promises.
interface Light { void on(); void off(); }
interface Lock { void lock(); void unlock(); }
interface Speaker { void play(String station); void stop(); }

// The brands' own code, unchanged.
class LumoLight { private final String room; LumoLight(String room) { this.room = room; } void setPower(boolean on) { IO.println("Lumo [" + room + "]: power " + (on ? "on" : "off")); } }
class BoltLock { private final String door; BoltLock(String door) { this.door = door; } void engage() { IO.println("Bolt [" + door + "]: ENGAGED"); } void release() { IO.println("Bolt [" + door + "]: RELEASED"); } }
class TuneoSpeaker { private final String room; TuneoSpeaker(String room) { this.room = room; } void startStream(String url) { IO.println("Tuneo [" + room + "]: streaming " + url); } void halt() { IO.println("Tuneo [" + room + "]: halted"); } }

// One adapter per brand: the hub's promise outside, the brand's words inside.
class LumoLightAdapter implements Light {
    private final LumoLight lumo;
    LumoLightAdapter(LumoLight lumo) { this.lumo = lumo; }
    public void on() { lumo.setPower(true); }
    public void off() { lumo.setPower(false); }
}

class BoltLockAdapter implements Lock {
    private final BoltLock bolt;
    BoltLockAdapter(BoltLock bolt) { this.bolt = bolt; }
    public void lock() { bolt.engage(); }
    public void unlock() { bolt.release(); }
}

class TuneoSpeakerAdapter implements Speaker {
    private final TuneoSpeaker tuneo;
    TuneoSpeakerAdapter(TuneoSpeaker tuneo) { this.tuneo = tuneo; }
    public void play(String station) { tuneo.startStream(station); }
    public void stop() { tuneo.halt(); }
}

// The hub only knows its own promises now.
class Hub {
    static final String NEWS = "https://tuneo.example/news";
    private final Light light;
    private final Lock door;
    private final Speaker speaker;

    Hub(Light light, Lock door, Speaker speaker) {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    void goodMorning() {
        IO.println("Good morning:");
        light.on();
        door.unlock();
        speaker.play(NEWS);
    }

    void leaveHome() {
        IO.println("Leaving home:");
        light.off();
        door.lock();
        speaker.stop();
    }
}

void main() {
    Hub hub = new Hub(
        new LumoLightAdapter(new LumoLight("kitchen")),
        new BoltLockAdapter(new BoltLock("front door")),
        new TuneoSpeakerAdapter(new TuneoSpeaker("kitchen")));
    hub.goodMorning();
    hub.leaveHome();
}
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
NEWS = "https://tuneo.example/news"


# The brands' own code, unchanged.
class LumoLight:
    def __init__(self, room): self.room = room
    def set_power(self, on): print(f"Lumo [{self.room}]: power {'on' if on else 'off'}")


class BoltLock:
    def __init__(self, door): self.door = door
    def engage(self): print(f"Bolt [{self.door}]: ENGAGED")
    def release(self): print(f"Bolt [{self.door}]: RELEASED")


class TuneoSpeaker:
    def __init__(self, room): self.room = room
    def start_stream(self, url): print(f"Tuneo [{self.room}]: streaming {url}")
    def halt(self): print(f"Tuneo [{self.room}]: halted")


# One adapter per brand: the hub's promise outside, the brand's words inside.
class LumoLightAdapter:
    def __init__(self, lumo):
        self.lumo = lumo

    def on(self):
        self.lumo.set_power(True)

    def off(self):
        self.lumo.set_power(False)


class BoltLockAdapter:
    def __init__(self, bolt):
        self.bolt = bolt

    def lock(self):
        self.bolt.engage()

    def unlock(self):
        self.bolt.release()


class TuneoSpeakerAdapter:
    def __init__(self, tuneo):
        self.tuneo = tuneo

    def play(self, station):
        self.tuneo.start_stream(station)

    def stop(self):
        self.tuneo.halt()


class Hub:
    """The hub only knows its own promises now: on/off, lock/unlock, play/stop."""

    def __init__(self, light, door, speaker):
        self.light = light
        self.door = door
        self.speaker = speaker

    def good_morning(self):
        print("Good morning:")
        self.light.on()
        self.door.unlock()
        self.speaker.play(NEWS)

    def leave_home(self):
        print("Leaving home:")
        self.light.off()
        self.door.lock()
        self.speaker.stop()


hub = Hub(
    LumoLightAdapter(LumoLight("kitchen")),
    BoltLockAdapter(BoltLock("front door")),
    TuneoSpeakerAdapter(TuneoSpeaker("kitchen")),
)
hub.good_morning()
hub.leave_home()
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
const NEWS = "https://tuneo.example/news";

// The brands' own code, unchanged.
class LumoLight { constructor(room) { this.room = room; } setPower(on) { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { constructor(door) { this.door = door; } engage() { console.log(`Bolt [${this.door}]: ENGAGED`); } release() { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { constructor(room) { this.room = room; } startStream(url) { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt() { console.log(`Tuneo [${this.room}]: halted`); } }

// One adapter per brand: the hub's promise outside, the brand's words inside.
class LumoLightAdapter {
  #lumo;
  constructor(lumo) { this.#lumo = lumo; }
  on() { this.#lumo.setPower(true); }
  off() { this.#lumo.setPower(false); }
}

class BoltLockAdapter {
  #bolt;
  constructor(bolt) { this.#bolt = bolt; }
  lock() { this.#bolt.engage(); }
  unlock() { this.#bolt.release(); }
}

class TuneoSpeakerAdapter {
  #tuneo;
  constructor(tuneo) { this.#tuneo = tuneo; }
  play(station) { this.#tuneo.startStream(station); }
  stop() { this.#tuneo.halt(); }
}

// The hub only knows its own promises now: on/off, lock/unlock, play/stop.
class Hub {
  constructor(light, door, speaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning() {
    console.log("Good morning:");
    this.light.on();
    this.door.unlock();
    this.speaker.play(NEWS);
  }

  leaveHome() {
    console.log("Leaving home:");
    this.light.off();
    this.door.lock();
    this.speaker.stop();
  }
}

const hub = new Hub(
  new LumoLightAdapter(new LumoLight("kitchen")),
  new BoltLockAdapter(new BoltLock("front door")),
  new TuneoSpeakerAdapter(new TuneoSpeaker("kitchen")),
);
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
// A module of its own (export {}), so this Lock isn't mixed up with the browser's built-in Lock type.
export {};

const NEWS = "https://tuneo.example/news";

// The hub's own promises.
interface Light { on(): void; off(): void; }
interface Lock { lock(): void; unlock(): void; }
interface Speaker { play(station: string): void; stop(): void; }

// The brands' own code, unchanged.
class LumoLight { private readonly room: string; constructor(room: string) { this.room = room; } setPower(on: boolean): void { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { private readonly door: string; constructor(door: string) { this.door = door; } engage(): void { console.log(`Bolt [${this.door}]: ENGAGED`); } release(): void { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { private readonly room: string; constructor(room: string) { this.room = room; } startStream(url: string): void { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt(): void { console.log(`Tuneo [${this.room}]: halted`); } }

// One adapter per brand: the hub's promise outside, the brand's words inside.
class LumoLightAdapter implements Light {
  private readonly lumo: LumoLight;
  constructor(lumo: LumoLight) { this.lumo = lumo; }
  on(): void { this.lumo.setPower(true); }
  off(): void { this.lumo.setPower(false); }
}

class BoltLockAdapter implements Lock {
  private readonly bolt: BoltLock;
  constructor(bolt: BoltLock) { this.bolt = bolt; }
  lock(): void { this.bolt.engage(); }
  unlock(): void { this.bolt.release(); }
}

class TuneoSpeakerAdapter implements Speaker {
  private readonly tuneo: TuneoSpeaker;
  constructor(tuneo: TuneoSpeaker) { this.tuneo = tuneo; }
  play(station: string): void { this.tuneo.startStream(station); }
  stop(): void { this.tuneo.halt(); }
}

// The hub only knows its own promises now.
class Hub {
  private readonly light: Light;
  private readonly door: Lock;
  private readonly speaker: Speaker;

  constructor(light: Light, door: Lock, speaker: Speaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning(): void {
    console.log("Good morning:");
    this.light.on();
    this.door.unlock();
    this.speaker.play(NEWS);
  }

  leaveHome(): void {
    console.log("Leaving home:");
    this.light.off();
    this.door.lock();
    this.speaker.stop();
  }
}

const hub = new Hub(
  new LumoLightAdapter(new LumoLight("kitchen")),
  new BoltLockAdapter(new BoltLock("front door")),
  new TuneoSpeakerAdapter(new TuneoSpeaker("kitchen")),
);
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted

The same eight lines, from a different shape. The hub's routines now say on(), unlock() and play(station), its own words, and its constructor asks for any Light, Lock and Speaker. The brands' classes didn't change at all. Each brand's words live in exactly one small class, at the edge.

Sam's new bedroom speaker is now one new adapter, and nothing in the hub changes. The same goes for the wall panel and the voice control when they're written: they'll use the hub's three promises too.

Where the languages differ. C#, Java and TypeScript write the promises as interfaces, and the compiler checks that each adapter keeps them. Python and JavaScript have no interface keyword: an adapter keeps the promise by having the right methods, and the hub calls them (that's duck typing). The TypeScript tab starts with export {};: TypeScript already knows a browser type called Lock, and a file of its own (a module) keeps the hub's Lock from being mixed up with it.

How it got its name

Teams connecting their code to someone else's kept writing the same small in-between class, so it got a name: an adapter, from the everyday word for something that makes one thing fit another. It's in the original 1994 book of patterns as the Adapter pattern (also called a wrapper, because it wraps the object that doesn't fit). The wrapped object is often called the adaptee, and the interface your code expects is the target.

The version here holds the object it adapts, which is called an object adapter. The book also describes a class adapter, made by subclassing the brand's class, which is the second fix under What would you try?: it works only when the brand allows it, so the object adapter is the one you'll usually write.

The modern version: an adapter in one expression

An adapter's whole job is "when the hub says on(), say setPower(true)". In today's languages that can be one object, made right where the device is set up, from two small functions. The hub doesn't change:

LumoLight lumo = new LumoLight("kitchen");
BoltLock bolt = new BoltLock("front door");
TuneoSpeaker tuneo = new TuneoSpeaker("kitchen");

Hub hub = new Hub(
    new LightFrom(() => lumo.SetPower(true), () => lumo.SetPower(false)),
    new LockFrom(() => bolt.Engage(), () => bolt.Release()),
    new SpeakerFrom(station => tuneo.StartStream(station), () => tuneo.Halt()));
hub.GoodMorning();
hub.LeaveHome();

interface ILight { void On(); void Off(); }
interface ILock { void Lock(); void Unlock(); }
interface ISpeaker { void Play(string station); void Stop(); }

// Small records that turn functions into the hub's promises, for any brand.
record LightFrom(Action TurnOn, Action TurnOff) : ILight { public void On() => TurnOn(); public void Off() => TurnOff(); }
record LockFrom(Action DoLock, Action DoUnlock) : ILock { public void Lock() => DoLock(); public void Unlock() => DoUnlock(); }
record SpeakerFrom(Action<string> DoPlay, Action DoStop) : ISpeaker { public void Play(string station) => DoPlay(station); public void Stop() => DoStop(); }

class Hub
{
    private const string News = "https://tuneo.example/news";
    private readonly ILight light;
    private readonly ILock door;
    private readonly ISpeaker speaker;

    public Hub(ILight light, ILock door, ISpeaker speaker)
    {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    public void GoodMorning() { Console.WriteLine("Good morning:"); light.On(); door.Unlock(); speaker.Play(News); }
    public void LeaveHome() { Console.WriteLine("Leaving home:"); light.Off(); door.Lock(); speaker.Stop(); }
}

class LumoLight { private readonly string room; public LumoLight(string room) { this.room = room; } public void SetPower(bool on) => Console.WriteLine(quot;Lumo [{room}]: power {(on ? "on" : "off")}"); }
class BoltLock { private readonly string door; public BoltLock(string door) { this.door = door; } public void Engage() => Console.WriteLine(quot;Bolt [{door}]: ENGAGED"); public void Release() => Console.WriteLine(quot;Bolt [{door}]: RELEASED"); }
class TuneoSpeaker { private readonly string room; public TuneoSpeaker(string room) { this.room = room; } public void StartStream(string url) => Console.WriteLine(quot;Tuneo [{room}]: streaming {url}"); public void Halt() => Console.WriteLine(quot;Tuneo [{room}]: halted"); }
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
interface Light { void on(); void off(); }
interface Lock { void lock(); void unlock(); }
interface Speaker { void play(String station); void stop(); }

class LumoLight { private final String room; LumoLight(String room) { this.room = room; } void setPower(boolean on) { IO.println("Lumo [" + room + "]: power " + (on ? "on" : "off")); } }
class BoltLock { private final String door; BoltLock(String door) { this.door = door; } void engage() { IO.println("Bolt [" + door + "]: ENGAGED"); } void release() { IO.println("Bolt [" + door + "]: RELEASED"); } }
class TuneoSpeaker { private final String room; TuneoSpeaker(String room) { this.room = room; } void startStream(String url) { IO.println("Tuneo [" + room + "]: streaming " + url); } void halt() { IO.println("Tuneo [" + room + "]: halted"); } }

class Hub {
    static final String NEWS = "https://tuneo.example/news";
    private final Light light;
    private final Lock door;
    private final Speaker speaker;

    Hub(Light light, Lock door, Speaker speaker) {
        this.light = light;
        this.door = door;
        this.speaker = speaker;
    }

    void goodMorning() { IO.println("Good morning:"); light.on(); door.unlock(); speaker.play(NEWS); }
    void leaveHome() { IO.println("Leaving home:"); light.off(); door.lock(); speaker.stop(); }
}

void main() {
    LumoLight lumo = new LumoLight("kitchen");
    BoltLock bolt = new BoltLock("front door");
    TuneoSpeaker tuneo = new TuneoSpeaker("kitchen");

    // Anonymous classes: an adapter written right where it's needed.
    Hub hub = new Hub(
        new Light() {
            public void on() { lumo.setPower(true); }
            public void off() { lumo.setPower(false); }
        },
        new Lock() {
            public void lock() { bolt.engage(); }
            public void unlock() { bolt.release(); }
        },
        new Speaker() {
            public void play(String station) { tuneo.startStream(station); }
            public void stop() { tuneo.halt(); }
        });
    hub.goodMorning();
    hub.leaveHome();
}
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
from types import SimpleNamespace

NEWS = "https://tuneo.example/news"


class LumoLight:
    def __init__(self, room): self.room = room
    def set_power(self, on): print(f"Lumo [{self.room}]: power {'on' if on else 'off'}")


class BoltLock:
    def __init__(self, door): self.door = door
    def engage(self): print(f"Bolt [{self.door}]: ENGAGED")
    def release(self): print(f"Bolt [{self.door}]: RELEASED")


class TuneoSpeaker:
    def __init__(self, room): self.room = room
    def start_stream(self, url): print(f"Tuneo [{self.room}]: streaming {url}")
    def halt(self): print(f"Tuneo [{self.room}]: halted")


class Hub:
    def __init__(self, light, door, speaker):
        self.light, self.door, self.speaker = light, door, speaker

    def good_morning(self):
        print("Good morning:")
        self.light.on()
        self.door.unlock()
        self.speaker.play(NEWS)

    def leave_home(self):
        print("Leaving home:")
        self.light.off()
        self.door.lock()
        self.speaker.stop()


lumo = LumoLight("kitchen")
bolt = BoltLock("front door")
tuneo = TuneoSpeaker("kitchen")

# An object made from small functions: an adapter written right where it's needed.
hub = Hub(
    SimpleNamespace(on=lambda: lumo.set_power(True), off=lambda: lumo.set_power(False)),
    SimpleNamespace(lock=bolt.engage, unlock=bolt.release),
    SimpleNamespace(play=tuneo.start_stream, stop=tuneo.halt),
)
hub.good_morning()
hub.leave_home()
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
const NEWS = "https://tuneo.example/news";

class LumoLight { constructor(room) { this.room = room; } setPower(on) { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { constructor(door) { this.door = door; } engage() { console.log(`Bolt [${this.door}]: ENGAGED`); } release() { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { constructor(room) { this.room = room; } startStream(url) { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt() { console.log(`Tuneo [${this.room}]: halted`); } }

class Hub {
  constructor(light, door, speaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning() { console.log("Good morning:"); this.light.on(); this.door.unlock(); this.speaker.play(NEWS); }
  leaveHome() { console.log("Leaving home:"); this.light.off(); this.door.lock(); this.speaker.stop(); }
}

const lumo = new LumoLight("kitchen");
const bolt = new BoltLock("front door");
const tuneo = new TuneoSpeaker("kitchen");

// Object literals: an adapter written right where it's needed.
const hub = new Hub(
  { on: () => lumo.setPower(true), off: () => lumo.setPower(false) },
  { lock: () => bolt.engage(), unlock: () => bolt.release() },
  { play: (station) => tuneo.startStream(station), stop: () => tuneo.halt() },
);
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted
// A module of its own (export {}), so this Lock isn't mixed up with the browser's built-in Lock type.
export {};

const NEWS = "https://tuneo.example/news";

interface Light { on(): void; off(): void; }
interface Lock { lock(): void; unlock(): void; }
interface Speaker { play(station: string): void; stop(): void; }

class LumoLight { private readonly room: string; constructor(room: string) { this.room = room; } setPower(on: boolean): void { console.log(`Lumo [${this.room}]: power ${on ? "on" : "off"}`); } }
class BoltLock { private readonly door: string; constructor(door: string) { this.door = door; } engage(): void { console.log(`Bolt [${this.door}]: ENGAGED`); } release(): void { console.log(`Bolt [${this.door}]: RELEASED`); } }
class TuneoSpeaker { private readonly room: string; constructor(room: string) { this.room = room; } startStream(url: string): void { console.log(`Tuneo [${this.room}]: streaming ${url}`); } halt(): void { console.log(`Tuneo [${this.room}]: halted`); } }

class Hub {
  private readonly light: Light;
  private readonly door: Lock;
  private readonly speaker: Speaker;

  constructor(light: Light, door: Lock, speaker: Speaker) {
    this.light = light;
    this.door = door;
    this.speaker = speaker;
  }

  goodMorning(): void { console.log("Good morning:"); this.light.on(); this.door.unlock(); this.speaker.play(NEWS); }
  leaveHome(): void { console.log("Leaving home:"); this.light.off(); this.door.lock(); this.speaker.stop(); }
}

const lumo = new LumoLight("kitchen");
const bolt = new BoltLock("front door");
const tuneo = new TuneoSpeaker("kitchen");

// Object literals the compiler checks against the hub's promises.
const hub = new Hub(
  { on: () => lumo.setPower(true), off: () => lumo.setPower(false) },
  { lock: () => bolt.engage(), unlock: () => bolt.release() },
  { play: (station) => tuneo.startStream(station), stop: () => tuneo.halt() },
);
hub.goodMorning();
hub.leaveHome();
Good morning:
Lumo [kitchen]: power on
Bolt [front door]: RELEASED
Tuneo [kitchen]: streaming https://tuneo.example/news
Leaving home:
Lumo [kitchen]: power off
Bolt [front door]: ENGAGED
Tuneo [kitchen]: halted

The same eight lines again. JavaScript and TypeScript write the adapter as an object literal, and TypeScript checks it against Light. Python's SimpleNamespace is an object built from named values, here the brand's own methods. Java writes an anonymous class (a class with no name, written where it's used). C# can't write an interface's methods inline, so three tiny records turn any two functions into a Light, a Lock or a Speaker, for every brand from now on.

Which to choose? The one-expression adapter is handy when the translation is one call per method. When it needs real work (turning Fahrenheit into Celsius, or a status like "ENGAGED" into true), or you want to test it on its own, give it a class with a name.

Where you've already used it

  • Java's new InputStreamReader(System.in) makes a stream of raw bytes look like a reader of characters, and Arrays.asList(array) makes an array look like a List.
  • C#'s new StreamReader(stream) does the same for a Stream: the stream's bytes, read as text.
  • Node's util.promisify(fs.readFile) takes a function written in the old callback style and hands back one that keeps today's promise-based shape.
  • Python's io.TextIOWrapper(binary_file) makes a file of bytes read as text.

When not to use it

  • When you own both sides. If the class that doesn't fit is your own, rename its method instead. An adapter is for code you can't, or shouldn't, change.
  • When the shapes are far apart. If the brand has no way to do what your interface promises (a light with no off switch), an adapter can only fake it. That's a design question, not a translation.
  • When it starts making decisions. An adapter that also caches, checks permissions or retries is doing more than translating; the next chapter shows the patterns for those jobs.

The cost is one small class per thing that doesn't fit, and one more hop to follow when you read the code.

How often you'll meet it: every day (our estimate: any code that talks to another company's library or service has adapters somewhere, often called "clients" or "wrappers").

Check yourself

2 questions to try on the lesson page.

So what

When code you can't change has the wrong shape, don't let its words spread through yours. Put one small adapter at the edge that keeps your promise and speaks theirs, and the next brand is one new class.

Key terms

Cheat sheets