Adapter Desing Patter Under 1 minute - Software Desing Pattern


Real-World Analogy
Think of an electrical adapter for charging your phone while traveling abroad. The wall socket’s shape varies between countries, and your charger may not fit. Instead of buying a new charger, you use an adapter that connects your charger’s plug with the foreign socket. The adapter enables compatibility without altering the socket or the charger.
Example: Adapter Design Pattern in Software
Suppose you have existing code using an old printer (LegacyPrinter
), but your new application expects a Printer
interface with a different method signature.
Goal: Adapt LegacyPrinter
so it can be used where Printer
is expected.
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print(self, message):
pass
class LegacyPrinter:
def print_document(self, text):
print(f"LegacyPrinter prints: {text}")
class PrinterAdapter(Printer):
def __init__(self, legacy_printer):
self.legacy_printer = legacy_printer
def print(self, message):
# Translate the new interface call to the legacy method
self.legacy_printer.print_document(message)
def client_code(printer: Printer):
printer.print("Hello, Adapter Pattern!")
# Usage:
legacy = LegacyPrinter()
adapter = PrinterAdapter(legacy)
client_code(adapter)
Works well when you cannot change external libraries or legacy systems.
✅ Advantages:
Allows integration with legacy code
Promotes code reusability
Keeps original code untouched
⚠️ Pitfalls:
- Too many adapters can clutter the design
Subscribe to my newsletter
Read articles from Rahul Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
