Adapt Interfaces and Swap Strategies
Core idea
An adapter translates an existing interface into the contract a caller expects. A strategy is a replaceable algorithm behind a common callable or method contract. Both reduce coupling, but an adapter addresses interface mismatch while a strategy addresses behavior choice. Functions are sufficient for many small strategies.
class Legacy: def read_cents(self): return {'amount': 350}def amount(source): return source.read_cents()['amount']print(amount(Legacy()))The adapter exposes an integer amount while the legacy representation remains private.
Expected output:
350Choose a pricing strategy
def quote(units, rate): return rate(units)def standard(n): return n * 5def bulk(n): return n * 3print(quote(4, standard), quote(4, bulk))Both strategies accept the same quantity and return the same unit of money.
Expected output:
20 12Common mistake
Do not hide different units or error conventions behind identical names. Document the common contract, including valid inputs and returned units.
Practice
Adapt a source returning text digits into an integer reader; use two alternative sorting-key strategies with the same records.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Adapter and strategy
Check your understanding of adapter and strategy.
What is printed?
def adapt(raw): return int(raw["n"])print(adapt({"n":"8"}))What is printed?
def run(fn): return fn(3)print(run(lambda n:n+5))What does an adapter solve?
What must interchangeable strategies share?