Jonas Kemper

Design Patterns with Python Examples - Part 2 - The Adapter Pattern in Python

Overview: The Adapter pattern allows two incompatible interfaces to work together by wrapping one inside another.

Example Use Case: Integrating a third-party payment processor with your internal billing interface.

class OldPaymentGateway:
    def make_payment(self, amount):
        print(f"Processed payment of ${amount} through Old Gateway.")

class NewPaymentSystem:
    def send(self, amount):
        print(f"Processed payment of ${amount} through New System.")

class PaymentAdapter:
    def __init__(self, new_system: NewPaymentSystem):
        self.new_system = new_system

    def make_payment(self, amount):
        self.new_system.send(amount)

old_gateway = OldPaymentGateway()
old_gateway.make_payment(50)

adapter = PaymentAdapter(NewPaymentSystem())
adapter.make_payment(75)

Why it’s useful: Let's you adopt new systems or APIs without rewriting existing code.