What you will learn
- How structural patterns combine objects behind a stable interface.
- Adapter for third-party APIs, decorator for stackable behaviour, proxy for controlled access.
- How to tell decorator and proxy apart.
The setup
Our checkout depends on a PaymentGateway interface with pay(amount_rupees). A vendor’s bank SDK has a different shape: it wants paise and returns a dictionary. We want logging and retries too, without changing the SDK or the checkout.
"""Structural patterns: adapter, decorator and proxy."""
import time
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def pay(self, amount_rupees: float) -> str: ...
# --- Adapter: make a third-party API fit our interface ---------------------------
class LegacyBankSdk:
"""Imagine this is a vendor library we can't change: wants paise and returns a dict."""
def make_transfer(self, paise: int, currency: str) -> dict:
return {"status": "OK", "ref": f"TXN-{paise}-{currency}"}
class BankAdapter(PaymentGateway):
def __init__(self, sdk: LegacyBankSdk):
self.sdk = sdk
def pay(self, amount_rupees):
result = self.sdk.make_transfer(round(amount_rupees * 100), "INR")
if result["status"] != "OK":
raise RuntimeError("payment failed")
return result["ref"]
# --- Decorator: add behaviour by wrapping, same interface -----------------------
class LoggingGateway(PaymentGateway):
def __init__(self, inner: PaymentGateway):
self.inner = inner
def pay(self, amount_rupees):
print(f"paying Rs {amount_rupees}")
ref = self.inner.pay(amount_rupees)
print(f"paid, ref {ref}")
return ref
class RetryingGateway(PaymentGateway):
def __init__(self, inner: PaymentGateway, attempts=3):
self.inner, self.attempts = inner, attempts
def pay(self, amount_rupees):
for attempt in range(1, self.attempts + 1):
try:
return self.inner.pay(amount_rupees)
except RuntimeError:
if attempt == self.attempts:
raise
time.sleep(0.01 * attempt)
# --- Proxy: control access to an expensive object (here, lazy + cached) ---------
class ExchangeRates:
def __init__(self):
print("(loading rates from a slow service...)")
self.rates = {"USD": 83.2, "EUR": 90.1}
def rate(self, currency):
return self.rates[currency]
class LazyRatesProxy:
def __init__(self):
self._real = None
def rate(self, currency):
if self._real is None: # create the real object only when first needed
self._real = ExchangeRates()
return self._real.rate(currency)
if __name__ == "__main__":
gateway = LoggingGateway(RetryingGateway(BankAdapter(LegacyBankSdk())))
gateway.pay(499.99)
rates = LazyRatesProxy()
print("proxy created, nothing loaded yet")
print(rates.rate("USD"), rates.rate("EUR"))
Output:
paying Rs 499.99
paid, ref TXN-49999-INR
proxy created, nothing loaded yet
(loading rates from a slow service...)
83.2 90.1
Adapter
BankAdapter implements our interface and translates to their API: rupees to paise, dictionary to reference string, status to exception. The rest of the codebase never sees LegacyBankSdk. When you switch vendors, you write one new adapter.
Use it whenever you integrate something you don’t control: payment providers, cloud SDKs, old internal services.
Decorator
LoggingGateway and RetryingGateway implement the same interface and wrap another gateway. Because they share the interface, they stack in any order:
gateway = LoggingGateway(RetryingGateway(BankAdapter(LegacyBankSdk())))
Each wrapper adds exactly one concern (Single Responsibility), and no class has to subclass every combination (LoggingRetryingBankGateway…). Order matters: logging outside retries logs once per payment; logging inside retries would log every attempt.
Python’s @decorator syntax for functions is the same idea applied to functions. Java’s BufferedReader(new FileReader(...)) is the classic library example.
Proxy
LazyRatesProxy has the same rate() method as ExchangeRates but controls access to it: the expensive object is created on first use. Other proxies:
- Caching proxy: remember results of slow calls.
- Protection proxy: check permissions before forwarding.
- Remote proxy: a local object that forwards calls over the network (RPC client stubs).
Decorator vs proxy: structurally similar (both wrap and forward). A decorator adds behaviour and is usually composed by the client; a proxy controls access to a subject and often manages its lifecycle.
Others worth knowing by name
- Facade: one simple interface over a complicated subsystem (
VideoConverter.convert(file, "mp4")hiding codecs and buffers). - Composite: treat individual objects and groups uniformly (files and folders both have
size()).
Key takeaways
- Adapter converts an interface you don’t control into one you do.
- Decorators add one concern each and stack because they share the interface; order matters.
- Proxies control access: lazy loading, caching, permission checks, remote calls.
Exercises
- Write a
CachingRatesProxythat refreshes rates when they are older than 60 seconds. - Make the SDK fail randomly 50% of the time and show that
RetryingGatewayrecovers. - Design a
Compositefor a file system whereFolder.size()sums its children.
Quiz
- Which pattern lets you switch payment vendors without touching checkout code?
- Why does the order of decorators matter?
- How does a proxy differ from a decorator?
Show answers
- Adapter: write a new adapter implementing
PaymentGatewayfor the new vendor. - Each wrapper sees the calls made by the layer outside it; logging outside retries logs once per payment, logging inside logs every attempt.
- A proxy controls access to its subject (lazy creation, caching, permissions); a decorator adds behaviour. Their structure is similar.