Problem Statement
When integrating two systems or components that have incompatible interfaces, direct communication fails. This causes errors or forces rewriting existing code, increasing time and cost.
┌─────────────┐ ┌───────────────┐ ┌─────────────┐ │ Client │─────▶│ Adapter │─────▶│ Adaptee │ │ (expects │ │ (translates │ │ (incompatible│ │ Target API) │ │ interface) │ │ interface) │ └─────────────┘ └───────────────┘ └─────────────┘
This diagram shows the client calling the adapter, which translates calls to the adaptee's incompatible interface.
### Before Adapter (incompatible interface) class OldPrinter: def print_text(self, text): print(f"Old Printer: {text}") class Client: def __init__(self, printer): self.printer = printer def print(self, message): # Expects method named 'print' self.printer.print(message) printer = OldPrinter() client = Client(printer) # This will fail because OldPrinter has no 'print' method # client.print("Hello") ### After Adapter class PrinterAdapter: def __init__(self, old_printer): self.old_printer = old_printer def print(self, message): self.old_printer.print_text(message) printer = OldPrinter() adapter = PrinterAdapter(printer) client = Client(adapter) client.print("Hello") # Works correctly