Adapter Pattern — ELI5
You’re traveling to another country and your phone charger doesn’t fit the wall outlet. The shape is wrong. You don’t redesign your charger or rewire the hotel — you use a plug adapter. It sits between your charger and the outlet, translating one shape into another.
The Adapter Pattern in Python does exactly the same thing for code. You have two pieces that need to work together, but their interfaces don’t match. One expects data as a dictionary, the other gives it as a list of tuples. One calls a method named fetch(), the other has get_data(). They’re doing similar things, but they speak different languages.
An adapter is a small piece of code that sits in the middle and translates. It takes calls in one format and converts them to the other format. Neither side needs to change — the adapter handles the mismatch.
This happens all the time in real projects. You’re using a payment library that returns results one way, but your app expects them another way. Instead of rewriting either piece, you write a thin adapter that bridges the gap.
The beauty is that both sides stay clean and unaware of each other. If you swap the payment library later, you only change the adapter — everything else stays the same.
The one thing to remember: An adapter makes two incompatible pieces of code work together without changing either one — just like a travel plug adapter connects your charger to a foreign outlet.
See Also
- Python Bridge Pattern Why separating what something does from how it does it keeps your Python code from becoming a tangled mess.
- Python Builder Pattern Why building complex Python objects step by step beats cramming everything into one giant constructor.
- Python Composite Pattern How the Composite Pattern lets you treat a group of things the same way you'd treat a single thing in Python.
- Python Facade Pattern How the Facade Pattern gives you one simple button instead of a confusing control panel in Python.
- Python Flyweight Pattern How the Flyweight Pattern saves memory by sharing common data instead of copying it thousands of times.