Lesson 5 of 28Principles
Structural Patterns
Wrap, combine and simplify objects with Adapter, Decorator, Facade, Proxy, Composite, Bridge and Flyweight in Python and TypeScript.
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.
Press Run (⌘ Enter) to see what happens.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.
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:
- Shape. Vendor field names and nesting become your types (
Charge,StoredFile). - Units. Cents vs dollar strings, seconds vs milliseconds, ISO strings vs
datetime. - 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. - 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.
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.
S3FileStore.load lets ClientError from the SDK escape, and InvoiceService catches it to show a 404 page. What is the main problem?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.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.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)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.
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__)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:
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.
Press Run (⌘ Enter) to see what happens.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.
Press Run (⌘ Enter) to see what happens.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.
Leaves (files) return their own size: 8 and 10.
Press Run (⌘ Enter) to see what happens.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.
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.
PdfInvoice, CsvInvoice, PdfReceipt and CsvReceipt, and product wants HTML output and a refund note. What does Bridge suggest?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.
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
| Pattern | Interface it exposes | Why it exists |
|---|---|---|
| Adapter | A different one (yours) | Make a foreign API fit |
| Decorator | The same one | Add behaviour (cache, log, retry) |
| Proxy | The same one | Control access (lazy, auth, remote) |
| Facade | A simpler one | Hide a whole subsystem |
| Composite | The same for one and many | Treat trees uniformly |
| Bridge | Two separate ones, joined by a field | Stop two axes of variation multiplying classes |
| Flyweight | The same, with shared state inside | Save memory across many similar objects |
Match each scenario to the pattern.
RateLimitedClient wraps ApiClient, has the same methods, and refuses calls beyond 10 per second. Which pattern is it closest to?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:
amtis a string of dollars. Convert it to whole cents (round to the nearest cent).curbecomes upper case.state(any case):SUCCEEDEDis"paid",FAILEDorDECLINEDis"failed", anything else is"pending".cardmay be missing ornull. Thenlast4isNone/null.
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- 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.