Skip to content
LLD Learn/Structural Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Adapter

5 min read

You'll learn to

  • -Wrap an incompatible interface so it can be used where a different interface is expected
  • -Distinguish object adapters from class adapters and know which one interview code favors

Adapter converts the interface of a class into another interface that the client expects, letting classes work together that otherwise could not because of incompatible interfaces. The canonical real-world analogy - a power plug adapter that lets a US device work in a European outlet - captures the pattern exactly: neither the device nor the outlet changes, a translator sits between them.

The Classic Trigger: Integrating a Third-Party Library

Adapter shows up constantly when your code expects one interface (say, PaymentGateway.charge(amount)) but a third-party library exposes a different one you cannot modify (LegacyBillingSDK.submit_transaction(cents, currency_code)). Rather than rewriting your calling code to match the third-party shape - or worse, rewriting the third-party library - you wrap it in an adapter that implements your expected interface and translates calls internally.

Wrapping an incompatible third-party interface
class PaymentGateway(ABC):        # the interface your code expects
    @abstractmethod
    def charge(self, amount_dollars: float) -> None: ...

class LegacyBillingSDK:            # third-party code you cannot modify
    def submit_transaction(self, cents: int, currency: str) -> None: ...

class LegacyBillingAdapter(PaymentGateway):
    def __init__(self, sdk: LegacyBillingSDK):
        self._sdk = sdk

    def charge(self, amount_dollars: float) -> None:
        self._sdk.submit_transaction(int(amount_dollars * 100), "USD")

Object Adapter vs. Class Adapter

The version above is an object adapter: it holds a reference to the wrapped object and delegates to it. A class adapter instead uses multiple inheritance, extending both the target interface and the adaptee simultaneously. Object adapters are strongly favored in interviews and in most real codebases: they work in languages without multiple inheritance, they can adapt any subclass of the adaptee (not just the exact type inherited from), and they keep the adaptee's internals fully encapsulated rather than exposed through inheritance.

Adapter is easy to confuse with Decorator (next chapter) since both wrap an object. The distinguishing question: does the wrapper change the interface (Adapter) or keep the same interface while adding behavior (Decorator)?

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

ScaleDojo Logo
Initializing ScaleDojo