Adapter Pattern in Python
Adapter lets incompatible code collaborate without changing the legacy or third-party class.
What is Adapter Pattern?
Adapter lets incompatible code collaborate without changing the legacy or third-party class.
Convert an existing interface into the interface a client expects.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class LegacyGateway:
# Adapter: wrap an incompatible API with the expected interface.
def make_payment(self, cents):
return f"PAY {cents / 100:.2f}"
class PaymentAdapter:
def __init__(self, gateway):
self.gateway = gateway
def pay(self, dollars):
# Translate both the method name and amount format.
return self.gateway.make_payment(round(dollars * 100))
gateway = PaymentAdapter(LegacyGateway())
print(gateway.pay(25))
Expected output
PAY 25.00
How it works
PaymentAdapter translates the modern pay call into the legacy make_payment call.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.