Docs

Design Patterns — Fast Recall (Python)

Adapter — make an incompatible interface fit


  • What: a wrapper that translates one object's interface into the one your code expects.
  • Why / when: integrating a third-party / legacy class whose method names don't match your interface — and you can't change it.
  • Analogy: a travel power plug — same electricity, different socket shape.
  • vs Facade: Adapter converts one interface to another; Facade simplifies a whole subsystem.
1class ThirdPartyLogger: # can't modify this 2 def write_log(self, text): print("LOG:", text) 3 4class LoggerAdapter: # exposes our interface 5 def __init__(self, ext): self.ext = ext 6 def log(self, msg): # what our app calls 7 self.ext.write_log(msg) # translate the call 8 9log = LoggerAdapter(ThirdPartyLogger()) 10log.log("hi") # LOG: hi