Skip to content

Lesson 5 of 28Principles

Structural Patterns

Wrap, combine and simplify objects with Adapter, Decorator, Facade, Proxy, Composite, Bridge and Flyweight in Python and TypeScript.

27 min read0/7 questions

Real systems are glued together from parts you did not design: a payment SDK with odd field names, a slow API that needs caching, an email service with six setup steps. Structural patterns are the standard ways to wrap and combine those parts so the rest of your code stays clean. Four of the five below are "a wrapper with a purpose", and telling them apart by purpose is what interviewers check.

Adapter: make a foreign shape fit yours

An Adapter converts one interface into the one your code expects. The classic case is a third-party SDK. Its response has its own names, units and status codes. If those leak into your business code, switching providers means rewriting everything. An adapter is the one place that knows the vendor's shape.

Python
from dataclasses import dataclass # Pretend this is the vendor's SDK. You cannot change it.class PayFastClient: def make_payment(self, amount_str: str, card_token: str) -> dict: return {"txn": "pf_81", "amt": amount_str, "state": "SUCCEEDED", "cur": "usd"} # Our model, used everywhere in our code.@dataclassclass Charge: id: str amount_cents: int currency: str status: str # "paid" | "failed" | "pending" class PayFastAdapter: STATUS = {"SUCCEEDED": "paid", "FAILED": "failed"} def __init__(self, client: PayFastClient): self.client = client def charge(self, amount_cents: int, token: str) -> Charge: raw = self.client.make_payment(f"{amount_cents / 100:.2f}", token) return Charge( id=raw["txn"], amount_cents=round(float(raw["amt"]) * 100), currency=raw["cur"].upper(), status=self.STATUS.get(raw["state"], "pending"), ) print(PayFastAdapter(PayFastClient()).charge(4999, "tok_1"))
Output
Press Run (⌘ Enter) to see what happens.

Notice the unit conversion ("49.99" string dollars to 4999 integer cents). Adapters are where those bugs get caught once instead of everywhere.

Quick check
Your team switches from PayFast to a new provider. With an adapter in place, what has to change?
Need a nudge? A hint rules out a wrong answer.

Adapter in the wild: wrapping a vendor SDK

The PayFast example converts one response. Real SDKs need more translation than that, and the adapter is where all of it belongs. When you wrap an SDK such as Stripe, boto3 for S3, or Twilio, the adapter has four jobs:

  1. Shape. Vendor field names and nesting become your types (Charge, StoredFile).
  2. Units. Cents vs dollar strings, seconds vs milliseconds, ISO strings vs datetime.
  3. Errors. The vendor's exception classes and error codes become your exceptions. If business code catches botocore.exceptions.ClientError, S3 has leaked into your domain, and you cannot swap it or fake it.
  4. Quirks. Pagination, retries on throttling, idempotency keys. Callers should never write a pagination loop for a vendor's list API.

The adapter implements an interface that your code owns (often called a port, a name you will meet again in hexagonal architecture). That interface is shaped by what your app needs, not by what the SDK happens to offer. Then you get a second payoff: a fast in-memory fake that implements the same port, and one test suite that both must pass.

Python
from typing import Protocol # ---- Pretend vendor SDK (shaped like boto3's S3 client). You cannot change it.class ClientError(Exception): def __init__(self, code: str): super().__init__(code) self.response = {"Error": {"Code": code}} class FakeS3Client: def __init__(self): self._objects: dict[tuple[str, str], bytes] = {} def put_object(self, *, Bucket: str, Key: str, Body: bytes) -> dict: self._objects[(Bucket, Key)] = Body return {"ETag": '"abc123"'} def get_object(self, *, Bucket: str, Key: str) -> dict: if (Bucket, Key) not in self._objects: raise ClientError("NoSuchKey") return {"Body": self._objects[(Bucket, Key)]} # ---- Our side: the port our business code depends on.class NotFound(Exception): pass class FileStore(Protocol): def save(self, path: str, data: bytes) -> None: ... def load(self, path: str) -> bytes: ... class S3FileStore: """Adapter: the only class that knows S3 exists.""" def __init__(self, client, bucket: str): self.client, self.bucket = client, bucket def save(self, path: str, data: bytes) -> None: self.client.put_object(Bucket=self.bucket, Key=path, Body=data) def load(self, path: str) -> bytes: try: return self.client.get_object(Bucket=self.bucket, Key=path)["Body"] except ClientError as e: if e.response["Error"]["Code"] == "NoSuchKey": raise NotFound(path) from e raise class InMemoryFileStore: """A fake for tests. Same port, no SDK at all.""" def __init__(self): self.files: dict[str, bytes] = {} def save(self, path: str, data: bytes) -> None: self.files[path] = data def load(self, path: str) -> bytes: if path not in self.files: raise NotFound(path) return self.files[path] # ---- One contract test, run against every implementation.def check_file_store(store: FileStore) -> str: store.save("invoices/1.pdf", b"%PDF") assert store.load("invoices/1.pdf") == b"%PDF" try: store.load("missing.pdf") except NotFound: return "ok" return "FAILED: missing file did not raise NotFound" print("in-memory:", check_file_store(InMemoryFileStore()))print("s3 adapter:", check_file_store(S3FileStore(FakeS3Client(), bucket="shop")))
Output
Press Run (⌘ Enter) to see what happens.

Look at what each piece buys you. Business code depends on FileStore and catches NotFound. Unit tests use InMemoryFileStore and run in microseconds. The contract test check_file_store keeps the fake honest: if the fake behaved differently from the adapter (say it returned None for a missing file), the shared test would catch it. In a real project you would also run that contract test against the real adapter with a local S3 emulator such as MinIO or LocalStack, in a slower test job.

A rule many teams follow: don't mock what you don't own. Mocking boto3 directly in tests couples every test to the SDK's call shapes, so an SDK upgrade breaks a hundred tests that were not about S3. Mock or fake your own port instead, and test the adapter once against the real thing.

Two warnings. Keep the adapter thin: translation only, no business rules, or it becomes a second service nobody tests. And do not build a "generic storage abstraction" that covers every feature of every cloud. Expose the four methods your app uses. You can add a fifth when you need it.

Quick check
Your S3FileStore.load lets ClientError from the SDK escape, and InvoiceService catches it to show a 404 page. What is the main problem?
Need a nudge? A hint rules out a wrong answer.

Decorator: add behaviour, keep the interface

A Decorator wraps an object and exposes the same interface, adding something before or after each call: caching, logging, retries, metrics. Because it looks identical to the original, callers cannot tell, and you can stack decorators.

Careful with the name. Python's @decorator syntax is a language feature for wrapping functions. It is the same idea applied to a function instead of an object, so both count, but they are not the same mechanism.

Python
import functools class RatesApi: def __init__(self): self.calls = 0 def rate(self, currency: str) -> float: self.calls += 1 # imagine a slow HTTP call here return {"EUR": 0.92, "GBP": 0.79}[currency] class CachedRates: # the Decorator pattern: same .rate() interface def __init__(self, inner): self.inner = inner self.cache: dict[str, float] = {} def rate(self, currency: str) -> float: if currency not in self.cache: self.cache[currency] = self.inner.rate(currency) return self.cache[currency] api = RatesApi()rates = CachedRates(api)for c in ["EUR", "EUR", "GBP", "EUR"]: rates.rate(c)print("API calls:", api.calls) # Python's @decorator syntax: the same idea for a functiondef logged(fn): @functools.wraps(fn) def wrapper(*args): result = fn(*args) print(f"{fn.__name__}{args} -> {result}") return result return wrapper @loggeddef convert(cents: int, rate: float) -> int: return round(cents * rate) convert(1000, 0.92)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

class Api:
  calls = 0
  def get(self, k):
      Api.calls += 1
      return k.upper()

class Cached:
  def __init__(self, inner):
      self.inner, self.memo = inner, {}
  def get(self, k):
      if k not in self.memo:
          self.memo[k] = self.inner.get(k)
      return self.memo[k]

c = Cached(Cached(Api()))
for k in ["a", "b", "a", "a", "b"]:
  c.get(k)
print(Api.calls)
Need a nudge? Hints walk you through it.

Python decorators and TypeScript decorators, in depth

The Decorator pattern wraps an object and keeps its interface. Python's @ syntax wraps a function (or a class) at definition time. Both add behaviour without editing the original, which is why they share a name, but they solve problems at different scales. The pattern is chosen at run time and per object: you can wrap one RatesApi instance in a cache and leave another unwrapped. The @ syntax is fixed when the module loads and applies to every call of that function.

Three things trip people up with Python decorators.

Stacking order. Decorators apply bottom up, and the result runs top down. The decorator nearest the def wraps first, so it ends up innermost.

Predict the outputPython

What does this print?

import functools

def tag(label):
  def deco(fn):
      @functools.wraps(fn)
      def wrapper(*args):
          return f"{label}({fn(*args)})"
      return wrapper
  return deco

@tag("a")
@tag("b")
def hello():
  return "hi"

print(hello(), hello.__name__)
Need a nudge? Hints walk you through it.

functools.wraps. Without it, every decorated function is called wrapper in tracebacks, logs and API docs, and tools that read signatures (FastAPI, pytest fixtures, Click) see the wrapper's *args, **kwargs instead of the real parameters. Always use it.

Decorators with arguments are a function that returns a decorator, which is why tag("a") above has three nested levels. If that reads as noise, a class with __call__ or a small functools.partial can be clearer.

TypeScript has decorators too, and there are two incompatible kinds. TypeScript 5.0 added support for the standard decorators from the TC39 proposal (Stage 3), which need no compiler flag. The older experimental decorators, enabled with experimentalDecorators in tsconfig.json, have a different signature and are what NestJS, Angular, TypeORM and many DI libraries still use, often together with emitDecoratorMetadata. Code written for one does not work with the other, so check which kind a framework expects before writing your own.

A standard method decorator receives the original method and a context object, and returns a replacement:

logged.ts (standard decorators, TS 5.0+)
function logged<This, Args extends unknown[], R>(
  target: (this: This, ...args: Args) => R,
  context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>,
) {
  const name = String(context.name);
  return function (this: This, ...args: Args): R {
    console.log(`-> ${name}(${args.join(", ")})`);
    return target.call(this, ...args);
  };
}
 
class Checkout {
  @logged
  pay(cents: number) {
    return `paid ${cents}`;
  }
}
 
new Checkout().pay(1200); // logs "-> pay(1200)"

Standard decorators cannot decorate function parameters (the @Inject() style you see in NestJS constructors), and they do not emit type metadata, which is why DI frameworks built on reflection still use the experimental flavour. For plain functions in TypeScript you do not need decorator syntax at all: a higher-order function like logged(fn) from the example above works everywhere.

Facade: one simple door into a complicated room

A Facade gives a simple interface to a messy subsystem. Placing an order touches inventory, payments, invoices and email. Instead of every route handler calling all four in the right order, one CheckoutFacade.place_order() does it.

Python
class Inventory: def reserve(self, sku): print(f"reserved {sku}")class Payments: def charge(self, cents): print(f"charged {cents}"); return "ch_1"class Mailer: def send(self, to, text): print(f"mailed {to}: {text}") class CheckoutFacade: def __init__(self, inventory, payments, mailer): self.inventory, self.payments, self.mailer = inventory, payments, mailer def place_order(self, sku: str, cents: int, email: str) -> str: self.inventory.reserve(sku) charge_id = self.payments.charge(cents) self.mailer.send(email, f"Order confirmed ({charge_id})") return charge_id CheckoutFacade(Inventory(), Payments(), Mailer()).place_order("MUG-1", 1200, "ada@example.com")
Output
Press Run (⌘ Enter) to see what happens.

You already use facades: requests.get(url) hides sockets, TLS and HTTP parsing. In the layered architecture lesson you will see that a service class is often a facade over repositories and gateways.

Proxy: same interface, controlled access

A Proxy stands in for a real object and controls access to it. Two common kinds: a lazy proxy delays creating something expensive until it is first used, and a protection proxy checks permissions before forwarding.

Python
class ReportStore: def __init__(self): print("(connecting to warehouse... slow)") def fetch(self, name: str) -> str: return f"<{name} data>" class LazyReportStore: def __init__(self): self._real = None def fetch(self, name: str) -> str: if self._real is None: self._real = ReportStore() return self._real.fetch(name) class AdminOnly: def __init__(self, inner, role: str): self.inner, self.role = inner, role def fetch(self, name: str) -> str: if self.role != "admin": raise PermissionError("admins only") return self.inner.fetch(name) store = AdminOnly(LazyReportStore(), role="admin")print("app started")print(store.fetch("revenue"))try: AdminOnly(LazyReportStore(), role="viewer").fetch("revenue")except PermissionError as e: print("blocked:", e)
Output
Press Run (⌘ Enter) to see what happens.

Proxy and Decorator look the same in code. The difference is intent: a decorator adds behaviour (caching, logging), a proxy guards the real object (when it is created, who may reach it). An ORM's lazy-loaded relationship (order.customer that queries only when touched) is a proxy you use every day.

Composite: treat one and many the same way

A Composite lets you treat a single item and a group of items through the same interface. A file has a size; a folder's size is the sum of its children, which may be files or more folders. Callers just ask size() and never check which kind they hold.

A folder tree is a composite
project/37 KB totalREADME.md3 KBapp.py12 KBdates.py8 KBmoney.py10 KButils/18 KBsrc/30 KBlogo.svg4 KBroot

Leaves (files) return their own size: 8 and 10.

1/4
Python
class File: def __init__(self, name: str, kb: int): self.name, self.kb = name, kb def size(self) -> int: return self.kb class Folder: def __init__(self, name: str, children: list): self.name, self.children = name, children def size(self) -> int: return sum(child.size() for child in self.children) project = Folder("project", [ File("README.md", 3), Folder("src", [File("app.py", 12), Folder("utils", [File("dates.py", 8), File("money.py", 10)])]), File("logo.svg", 4),])print(project.size())
Output
Press Run (⌘ Enter) to see what happens.

React is a composite too: a component renders either plain elements or other components, and React walks the whole tree the same way. Menus, org charts, comment threads and permission groups all fit this shape.

Bridge: two hierarchies joined by composition

Bridge solves a specific explosion. Say you have two kinds of message (alerts and digests) and two channels (email and Slack). With inheritance alone you write EmailAlert, SlackAlert, EmailDigest, SlackDigest. Add SMS and a weekly report and you have nine classes, each mixing two concerns. Bridge splits the two dimensions into separate hierarchies and connects them with a field: a message has a channel.

Python
class EmailChannel: def deliver(self, to: str, subject: str, body: str) -> str: return f"email {to}: [{subject}] {body}" class SlackChannel: def deliver(self, to: str, subject: str, body: str) -> str: return f"slack #{to}: *{subject}* {body}" # The "abstraction" side: what kind of message. It HAS a channel.class Alert: def __init__(self, channel): self.channel = channel def send(self, to: str, problem: str) -> str: return self.channel.deliver(to, "ALERT", problem.upper()) class Digest: def __init__(self, channel): self.channel = channel def send(self, to: str, items: list[str]) -> str: return self.channel.deliver(to, f"{len(items)} updates", "; ".join(items)) print(Alert(EmailChannel()).send("oncall@shop.dev", "disk full"))print(Alert(SlackChannel()).send("ops", "disk full"))print(Digest(SlackChannel()).send("team", ["deploy done", "2 new users"]))
Output
Press Run (⌘ Enter) to see what happens.

Now the count is additive: three message kinds plus three channels is six classes, not nine, and each class changes for one reason. If this looks like ordinary dependency injection, it is. Bridge is mostly a name for "favour composition over inheritance when a class varies along two independent axes". You see it in database drivers (one SQLAlchemy API, many dialects), logging (loggers and handlers are separate), and UI kits that separate a component from its rendering backend. The useful skill is spotting the explosion early: when class names start to look like a grid (PdfMonthlyReport, CsvMonthlyReport, PdfWeeklyReport), there are two hierarchies hiding in one.

Quick check
You have PdfInvoice, CsvInvoice, PdfReceipt and CsvReceipt, and product wants HTML output and a refund note. What does Bridge suggest?
Need a nudge? A hint rules out a wrong answer.

Flyweight: share the immutable part

Flyweight saves memory when you have huge numbers of similar objects. You split each object's state in two: the intrinsic part that many objects share and that never changes (a font and size), and the extrinsic part that is unique (which letter, where it is). The shared part is created once and handed out from a cache.

Python
from dataclasses import dataclass @dataclass(frozen=True)class Style: # the shared, immutable part font: str size: int bold: bool class StyleFactory: def __init__(self): self._cache: dict[tuple, Style] = {} def get(self, font: str, size: int, bold: bool = False) -> Style: key = (font, size, bold) if key not in self._cache: self._cache[key] = Style(font, size, bold) return self._cache[key] styles = StyleFactory()text = "Hello, flyweight world! " * 400# Each character keeps only its own data (the letter) plus a shared Style.chars = [(ch, styles.get("Inter", 14, bold=ch.isupper())) for ch in text] print("characters:", len(chars))print("distinct Style objects:", len({id(style) for _, style in chars}))
Output
Press Run (⌘ Enter) to see what happens.

The shared object must be immutable. If one character could change its Style, every character sharing it would change too. That is why the dataclass is frozen.

You rarely write a flyweight in web code, but you rely on them. CPython interns many short strings and caches small integers, so identical values can be the same object (an implementation detail, which is why you compare with ==, never is). sys.intern() lets you intern strings yourself when you hold millions of repeated keys. Game engines share one texture across thousands of sprites. In React, hoisting a constant element or style object outside a component means every render reuses the same object instead of allocating a new one. Reach for the pattern only when profiling shows memory is the problem.

Telling the wrappers apart

PatternInterface it exposesWhy it exists
AdapterA different one (yours)Make a foreign API fit
DecoratorThe same oneAdd behaviour (cache, log, retry)
ProxyThe same oneControl access (lazy, auth, remote)
FacadeA simpler oneHide a whole subsystem
CompositeThe same for one and manyTreat trees uniformly
BridgeTwo separate ones, joined by a fieldStop two axes of variation multiplying classes
FlyweightThe same, with shared state insideSave memory across many similar objects
Match the pairs0/5 matched

Match each scenario to the pattern.

Choose an item, then its match on the other side.
Quick check
RateLimitedClient wraps ApiClient, has the same methods, and refuses calls beyond 10 per second. Which pattern is it closest to?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Adapt a payment provider

A payment provider returns charges in its own shape. Write adapt_charge(raw) (TypeScript: adaptCharge(raw)) that maps it to our model.

raw:  {"txn": "pf_1", "amt": "49.99", "cur": "usd", "state": "SUCCEEDED", "card": {"last4": "4242"}}
ours: {"id": "pf_1", "cents": 4999, "currency": "USD", "status": "paid", "last4": "4242"}

Rules:

  • amt is a string of dollars. Convert it to whole cents (round to the nearest cent).
  • cur becomes upper case.
  • state (any case): SUCCEEDED is "paid", FAILED or DECLINED is "failed", anything else is "pending".
  • card may be missing or null. Then last4 is None / null.
def adapt_charge(raw: dict) -> dict: # Translate the provider's fields into {id, cents, currency, status, last4}. pass
ChallengeEasy

Caching decorator

CachingRateProvider wraps any rate provider (an object with rate(currency)) and has the same interface. This is the Decorator pattern.

  • rate(currency) asks the inner provider only the first time for each currency, then answers from its cache
  • if the inner provider raises, let the error through and do not cache anything, so the next call tries again
  • clear() empties the cache
api = SlowRatesApi()
rates = CachingRateProvider(api)
rates.rate("EUR"); rates.rate("EUR"); rates.rate("GBP")
# api was called twice: once for EUR, once for GBP
class CachingRateProvider: def __init__(self, inner): pass def rate(self, currency: str) -> float: pass def clear(self) -> None: pass
Key terms
adapter
A wrapper that converts a foreign interface (like a vendor SDK) into the one your code expects.
decorator (pattern)
A wrapper with the same interface that adds behaviour such as caching or logging, and can be stacked.
facade
A simple interface over a complicated subsystem, so callers make one call instead of many.
proxy
A stand-in with the same interface that controls access to the real object, for example lazily or by permission.
composite
A structure where single items and groups share one interface, so trees can be handled recursively.
port
An interface your own code defines for something external, such as file storage, that adapters implement.
contract test
One test suite run against every implementation of an interface, so fakes and real adapters behave the same.
bridge
Splitting two independent dimensions into separate hierarchies joined by composition, so classes add up instead of multiplying.
flyweight
Sharing one immutable object for the common part of many similar objects to save memory.