skipnothing/Design Patterns
UNIT 02

Structural Patterns

Decorator, Adapter, Facade, Proxy, patterns for combining objects

Structural patterns are about composition, how objects combine to form larger structures while keeping things flexible.

Loading…
TOPICS
#7

Decorator

Trade a 2^N subclass table for N wrappers that share one interface, stack compression and encryption around a file source in any order, and spot the same nesting in `new BufferedReader(new FileReader(f))` and Python's `open()`.

A `FileDataSource` with `read` and `write` ships fine, until someone wants compressed saves, then encrypted ones, then both. By the third option you're naming a `CompressedEncryptedFileDataSource` and the class names are multiplying faster than the features.

14 min
#8

Composite

Collapse a recursive `if isinstance(node, Folder)` into one `size()` that both files and folders answer, watch the type check leave the caller and become recursion on the container, and weigh the transparency-versus-safety cost of putting `add()` on every node.

Your `total_size(node)` function opens with `if isinstance(node, Folder)`, recurses into the children, and re-asks the same question at every level. Add a zip-archive node and you're back editing that one function, and every other function that walks the tree.

14 min
#9

Adapter

Wrap a vendor's `dispatch(to, body, opts)` so two hundred call sites keep calling `send(msg)`, watch the translation live entirely inside the wrapper, and tell it from a decorator by the one thing that differs: the interface changes, not the behaviour.

Your whole app calls `notify.send(msg)`. The SMS vendor you just signed names the same action dispatch, wants a recipient and an options bag, and there are two hundred call sites between you and a library you can't edit.

10 min
#10

Proxy

Front an expensive or guarded object with a same-interface stand-in that decides when to create it, whether to allow the call, or whether a cached answer is enough, and spot the shape in JS `new Proxy`, ORM lazy loads, and gRPC stubs.

A photo grid builds a full-resolution `HighResImage` for all two hundred files the moment the folder opens, decoding megabytes the user scrolls past. The screen shows nine at a time; the rest loaded for nothing.

12 min
#11

Facade

Route a handler's five service calls through one method so callers depend on one class instead of five, reach past it straight to a worker for the rare case the method skips, and split the front before it bloats into a god object.

A checkout handler calls `inventory.reserve`, then `payment.charge`, then `shipping.schedule`, then emails the buyer, in that exact order. Every screen that places an order copies the same five-step dance and imports all five classes.

12 min
All units