Design Patterns II — Structural
What you’ll learn. Seven structural patterns that govern how objects are assembled: Adapter, Decorator, Facade, Proxy, Composite, Bridge and Flyweight. Several look alike in a class diagram (they all wrap something), so the emphasis is on intent: what problem each solves and how to tell them apart. Code is Python or TypeScript, labelled.
The common shape: wrapping
Section titled “The common shape: wrapping”Most structural patterns involve an object that holds a reference to another and forwards calls. What differs is the reason:
| Pattern | Wrapper’s purpose | Interface of wrapper vs wrapped |
|---|---|---|
| Adapter | Make an incompatible interface usable | Different (translates) |
| Decorator | Add behavior dynamically | Same |
| Proxy | Control access to the object | Same |
| Facade | Simplify a subsystem | New, simpler |
| Composite | Treat tree of objects uniformly | Same (leaf and container) |
| Bridge | Vary abstraction and implementation independently | Two parallel hierarchies |
| Flyweight | Share state to save memory | Same |
If you can state the intent in one sentence, you can pick the right pattern; the name matters less than the reason.
Adapter
Section titled “Adapter”Problem. You have a class whose interface does not match what the client expects, and you cannot (or should not) change it: third-party SDKs, legacy code, different vendors.
Idea. Write a wrapper that implements the target interface by translating calls to the adaptee.
// TypeScript: adapt a vendor SDK to your own portinterface PaymentGateway { charge(amountCents: number, currency: string, token: string): Promise<{ id: string }>;}
// Third-party SDK with a different shapeclass StripeLikeClient { async createCharge(opts: { amount: number; currency: string; source: string }) { return { chargeId: "ch_123", status: "ok" }; }}
class StripeAdapter implements PaymentGateway { constructor(private client: StripeLikeClient) {} async charge(amountCents: number, currency: string, token: string) { const r = await this.client.createCharge({ amount: amountCents, currency: currency.toLowerCase(), source: token, }); return { id: r.chargeId }; }}Adapter is the workhorse of hexagonal architecture: every “adapter” there is literally this pattern, translating between your domain’s port and an external technology (Architecture Styles). It also contains vendor lock-in: swap vendors by writing one new adapter. It anchors an anti-corruption layer in domain-driven design: translate foreign models at the boundary so they do not leak into your domain.
Object adapters (composition, shown above) are preferred over class adapters (multiple inheritance).
Decorator
Section titled “Decorator”Problem. You want to add responsibilities to individual objects dynamically, without subclass explosion. If you have logging, caching, retry and auth, inheritance would need 2^4 subclasses.
Idea. Wrap an object in another with the same interface that adds behavior before/after delegating. Decorators stack.
# Python: object-oriented decorators on a shared interfacefrom typing import Protocol
class DataSource(Protocol): def read(self) -> str: ... def write(self, data: str) -> None: ...
class FileSource: def __init__(self, path): self.path = path def read(self): return open(self.path).read() def write(self, data): open(self.path, "w").write(data)
class Compressed: def __init__(self, inner: DataSource): self.inner = inner def read(self): return decompress(self.inner.read()) def write(self, data): self.inner.write(compress(data))
class Encrypted: def __init__(self, inner: DataSource): self.inner = inner def read(self): return decrypt(self.inner.read()) def write(self, data): self.inner.write(encrypt(data))
src = Encrypted(Compressed(FileSource("a.dat"))) # compose at runtimePython’s @decorator syntax is function wrapping, the same idea at the function level:
import functools, time
def retry(times=3, delay=0.1): def deco(fn): @functools.wraps(fn) def wrapper(*a, **kw): for attempt in range(times): try: return fn(*a, **kw) except ConnectionError: if attempt == times - 1: raise time.sleep(delay * 2 ** attempt) return wrapper return deco
@retry(times=4)def fetch(url): ...Middleware chains (Express/Koa, ASGI, gRPC interceptors) are Decorator applied to request handlers. Java’s InputStream wrappers (BufferedInputStream(new FileInputStream(...))) are the textbook case.
Pitfalls: order matters (encrypt then compress is useless; compress then encrypt works); many small wrappers are harder to debug; identity checks (is) break; a decorator that must know the concrete type of what it wraps is a design smell.
Facade
Section titled “Facade”Problem. A subsystem has many classes and a complex setup; clients need only a simple use case.
Idea. Provide a unified, higher-level interface that makes the subsystem easier to use. It does not prevent access to the underlying classes; it offers a convenient front door.
# Python: facade over a video conversion subsystemclass VideoFacade: def convert(self, path: str, fmt: str) -> str: video = VideoFile(path) codec = CodecFactory.for_format(video, fmt) audio = AudioMixer().fix(video) out = BitrateReader.convert(video, codec) return Muxer().mux(out, audio, fmt)
# clients: VideoFacade().convert("a.mov", "mp4")In this sense, requests.get(url) is a facade over urllib3, connection pools, TLS and redirect handling. Facade is Ousterhout’s “deep module” in pattern form: simple interface, lots hidden. Use it to define layer boundaries and to give legacy systems a clean API. The risk is a god facade that accretes every operation and couples everything to itself.
Facade vs Adapter: Facade simplifies many objects behind a new interface you design; Adapter conforms one object to an interface someone else defined.
Problem. You need to control access to an object, or defer, guard or instrument it, without clients knowing.
Idea. A surrogate with the same interface as the real object. Common varieties:
- Virtual proxy: lazy creation of an expensive object.
- Protection proxy: access control checks.
- Remote proxy: local stand-in for a remote object (gRPC/RPC stubs).
- Caching proxy: memoize results.
- Logging/smart reference: count references, record calls.
// TypeScript: caching + protection proxies on the same interfaceinterface Reports { get(id: string): Promise<string> }
class RemoteReports implements Reports { async get(id: string) { /* slow network call */ return `report-${id}`; }}
class CachingReports implements Reports { private cache = new Map<string, string>(); constructor(private inner: Reports) {} async get(id: string) { const hit = this.cache.get(id); if (hit !== undefined) return hit; const v = await this.inner.get(id); this.cache.set(id, v); return v; }}
class AuthorizedReports implements Reports { constructor(private inner: Reports, private canRead: (id: string) => boolean) {} async get(id: string) { if (!this.canRead(id)) throw new Error("forbidden"); return this.inner.get(id); }}JavaScript has a built-in Proxy object used by Vue 3’s reactivity and many ORMs (lazy-loaded relations). Python achieves it via __getattr__. ORMs’ lazy loading (a user.orders that hits the DB when first touched) is a virtual proxy, and it causes the notorious N+1 query problem (Databases).
Proxy vs Decorator. Structurally identical. Intent differs: a Decorator adds new behavior chosen by the client; a Proxy manages access/lifecycle of the same behavior, typically controlling when and whether the subject is reached, and often creating the subject itself. In practice the boundary is blurry; do not agonize.
Composite
Section titled “Composite”Problem. Data forms a part-whole tree (files and directories, UI widgets, expression trees, org charts), and clients want to treat a single item and a group of items uniformly.
Idea. A common component interface implemented by both leaves and composites; composites hold children of the component type and delegate recursively.
# Python: filesystem sizesfrom abc import ABC, abstractmethod
class Node(ABC): @abstractmethod def size(self) -> int: ...
class File(Node): def __init__(self, n: int): self.n = n def size(self): return self.n
class Folder(Node): def __init__(self, *children: Node): self.children = list(children) def size(self): return sum(c.size() for c in self.children)
tree = Folder(File(10), Folder(File(5), File(7)))assert tree.size() == 22Folder|- File(10)`- Folder |- File(5) `- File(7)Composite is the right model for ASTs, scene graphs, the DOM, permission groups, and nested menu structures. Design question: should add()/remove() live on the common interface (uniform but unsafe on leaves) or only on composites (safe but clients must distinguish)? Modern typed code typically puts child management on the composite only and uses sum types/visitors for traversal (see Behavioral Patterns).
Bridge
Section titled “Bridge”Problem. A class varies along two independent dimensions. E.g. shapes (circle, square) and renderers (vector, raster). Subclassing produces the cross product (VectorCircle, RasterCircle, VectorSquare, …), growing multiplicatively.
Idea. Split into two hierarchies, abstraction and implementation, and connect them by composition (the “bridge”). Each varies independently, so growth is additive: M + N classes instead of M x N.
// TypeScriptinterface Renderer { circle(x: number, y: number, r: number): string }class SvgRenderer implements Renderer { circle(x: number, y: number, r: number) { return `<circle cx="${x}" cy="${y}" r="${r}"/>`; }}class AsciiRenderer implements Renderer { circle(x: number, y: number, r: number) { return `(o) at ${x},${y} r=${r}`; }}
abstract class Shape { constructor(protected renderer: Renderer) {} abstract draw(): string;}class Circle extends Shape { constructor(r: Renderer, private x: number, private y: number, private radius: number) { super(r); } draw() { return this.renderer.circle(this.x, this.y, this.radius); }}
new Circle(new SvgRenderer(), 0, 0, 5).draw();Bridge is “prefer composition over inheritance” applied at design time (Adapter is the retrofit version, applied after the fact to make existing things fit). Familiar uses: JDBC/ODBC drivers (your code is the abstraction; drivers are implementations), logging frameworks (loggers vs appenders), device drivers, cross-platform UI. If you only have one variation axis, you do not need Bridge.
Flyweight
Section titled “Flyweight”Problem. A program creates enormous numbers of similar objects, and memory is the bottleneck.
Idea. Split object state into intrinsic (shared, immutable, context-independent) and extrinsic (varies per use, passed in by the client or stored outside). Share one flyweight object per distinct intrinsic state, typically via a factory/cache.
# Python: a text editor with millions of charactersclass GlyphStyle: # flyweight: intrinsic state (font, size, color) __slots__ = ("font", "size", "color") def __init__(self, font, size, color): self.font, self.size, self.color = font, size, color
class StyleFactory: _cache: dict[tuple, GlyphStyle] = {} @classmethod def get(cls, font, size, color) -> GlyphStyle: key = (font, size, color) if key not in cls._cache: cls._cache[key] = GlyphStyle(*key) return cls._cache[key]
# per-character extrinsic state: (char, position); style is shareddoc = [("H", 0, StyleFactory.get("Serif", 12, "black")), ("i", 1, StyleFactory.get("Serif", 12, "black"))]assert doc[0][2] is doc[1][2]Memory estimate: 1 million characters each with its own 3-field style object at ~100 bytes is ~100 MB; with 20 shared styles plus a pointer per character (8 bytes) it is ~8 MB.
You use flyweights all the time without naming them: Python interns small ints and many strings (sys.intern), Java has Integer.valueOf caching and string pools, game engines share meshes/textures across thousands of instances, and database columnar dictionary encoding is flyweight on disk. Requirements: flyweights must be immutable (shared mutable state is a bug factory) and the saving must be real; profile first (Reliability & Performance). Use __slots__ or dataclass slots in Python for per-object memory cuts.
Choosing and combining
Section titled “Choosing and combining”Patterns compose. A realistic HTTP client stack: a Facade (simple client.get()) over Decorators (retry, auth, logging) wrapping an Adapter over a vendor library, with a Proxy providing a cache. A UI is a Composite tree whose nodes use a Bridge to render to different backends.
Decision guide:
- Need to reuse something whose interface does not match: Adapter.
- Need to add or combine behaviors dynamically, same interface: Decorator.
- Need to hide complexity behind one simple entry point: Facade.
- Need to control or defer access: Proxy.
- Part-whole hierarchy treated uniformly: Composite.
- Two orthogonal axes of variation: Bridge.
- Many identical-ish objects, memory pressure: Flyweight.
Pitfalls
Section titled “Pitfalls”- Wrapper towers: stack traces and debugging suffer when ten layers delegate; keep chains short and name layers clearly.
- Leaky Adapter: letting vendor types appear in your domain defeats the purpose.
- Decorators that change contract (e.g., a caching layer that returns stale data where callers assumed freshness) violate Liskov substitutability.
- Facade as dumping ground.
- Premature Flyweight/Bridge: both pay off only with real scale or real multi-axis variation.
Key takeaways
Section titled “Key takeaways”- Structural patterns are about composition; most are wrappers distinguished by intent.
- Adapter translates an interface; Decorator adds behavior; Proxy controls access; Facade simplifies; Composite unifies leaf and group; Bridge decouples two axes of variation; Flyweight shares immutable state for memory.
- In Python/TypeScript, decorators/middleware and plain composition handle many cases natively.
- Always check that wrappers preserve the contract of the interface they present.
Exercises
Section titled “Exercises”- Conceptual. Explain the difference between Decorator and Proxy using a caching example. When would you call the same class either?
- Hands-on (Python). Write a
@timeddecorator for functions and aLoggingRepositoryobject decorator wrapping any repository withget/save. Compare their reuse and type-safety. - Hands-on (TypeScript). Model a UI of
Panel(containing widgets) andButtonas a Composite withrender(): stringandwidth(): number. Add aPanelinside aPanel. - Conceptual. You have 5 notification types and 4 delivery channels. How many classes with inheritance vs Bridge?
- Hands-on. Estimate memory saved by interning 10 million log records whose
levelfield takes 5 distinct string values (assume 60 bytes per distinct string copy vs an 8-byte reference).
Solutions (sketch)
- Decorator: client chooses to add caching, as an optional extra. Proxy: the proxy stands in for the subject and the client is unaware; typically also controls creation. The same class can be both; the label reflects intent.
- Function decorator is generic over signatures; the object decorator is bound to the repository interface but can add domain-specific logging.
Panel.width = sum(children width)+padding;renderjoins children renders, recursion handles nesting.- Inheritance: up to 5 x 4 = 20 concrete classes. Bridge: 5 + 4 = 9.
- Without interning: 10M x 60 B = 600 MB. With: 10M x 8 B + 5 x 60 B ~ 80 MB (about 7.5x smaller).
Further reading
Section titled “Further reading”- Gamma, Helm, Johnson, Vlissides, Design Patterns (1994), the structural chapter.
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (2nd ed., 2020).
- Refactoring.Guru’s pattern catalog (online reference, by Alexander Shvets).
- Alistair Cockburn, “Hexagonal Architecture” (2005), for the adapter as architecture.
- Eric Evans, Domain-Driven Design (2003), on anti-corruption layers.