StructuralPythonverifiedVerified

Adapter Pattern in Python

Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.

How to Implement the Adapter Pattern in Python

1Step 1: Define the target interface and the incompatible adaptee

from typing import Protocol


class Target(Protocol):
    def request(self) -> str: ...


class Adaptee:
    def specific_request(self) -> str:
        return "Adaptee: specific behaviour"

2Step 2: Implement the adapter that bridges both interfaces

class Adapter:
    def __init__(self, adaptee: Adaptee) -> None:
        self._adaptee = adaptee

    def request(self) -> str:
        result = self._adaptee.specific_request()[::-1]
        return f"Adapter: (translated) {result}"

3Step 3: Use the adapter transparently through the target interface

def client_code(target: Target) -> None:
    print(target.request())


adaptee = Adaptee()
print("Adaptee:", adaptee.specific_request())

adapter = Adapter(adaptee)
client_code(adapter)

Adapter Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Adapter Pattern in the Real World

A travel power adapter lets your American laptop plug (client) work in a European wall socket (adaptee) without modifying either. The adapter speaks both “languages”, translating the two-pin plug to the two-round-pin socket, making them interoperable without any changes on either side.