Design Patterns interview question · Most asked

What is the Adapter pattern? Give an example.

Summary

Adapter wraps a class that has an incompatible interface and translates calls to the interface your code expects. For example, a LegacyBillingAdapter implements your PaymentProvider.charge(cents) by converting cents to a dollar string and calling the legacy submit().

Longer Answer

The client sees only the target interface; all translation (method names, units, result shapes, error types) lives in the adapter. That keeps vendor-specific details out of business logic and makes it easy to switch or add providers.

Real examples: Laravel's filesystem adapters (local, S3, FTP behind one API), Java's InputStreamReader and Arrays.asList(), DB-API drivers in Python.

Code Example

class LegacyBilling:  # third-party: amount as a dollar string
    def submit(self, amount):
        return {"ref": f"LB-{amount}"}


class BillingAdapter:  # our interface: charge(cents) -> id
    def __init__(self, legacy):
        self.legacy = legacy

    def charge(self, cents):
        return self.legacy.submit(f"{cents // 100}.{cents % 100:02d}")["ref"]


print(BillingAdapter(LegacyBilling()).charge(1250))

Key Points

  • Translates an incompatible interface to the expected one.
  • Client stays unchanged.
  • Ideal for third-party and legacy code.
  • Keeps vendor types out of the domain.

Deep dive: Design Patterns, Explained Simply: Adapter

Explanation

What interviewers look for

Clear roles (target, adaptee, adapter), a realistic example, and the benefit of isolating vendor code.

Follow-up questions

  • How is Adapter different from Facade?
  • Class adapter vs object adapter?

More most-asked Design Patterns questions

← All Design Patterns questions