Lesson 3 of 9 · 23m
Structural and Behavioral Patterns: Composition and Flow
Adapters, facades, decorators, strategies, observers, and commands organize collaboration — or bury it under indirection.
Structural patterns shape how pieces fit together. Behavioral patterns shape how work moves between them. In healthy systems these patterns reduce coordination cost. In unhealthy systems they turn a simple call into a scavenger hunt through six interfaces.
Adapter: translate at the boundary
An adapter converts an external shape into the shape your domain wants. It is most valuable at system edges: vendor SDKs, legacy APIs, incompatible persistence models.
interface Payments {
charge(customerId: string, cents: number): Promise<PaymentResult>;
}
class StripePayments implements Payments {
constructor(private stripe: StripeClient) {}
async charge(customerId: string, cents: number) {
const intent = await this.stripe.paymentIntents.create({
amount: cents,
currency: "usd",
customer: customerId,
confirm: true,
});
return { id: intent.id, ok: intent.status === "succeeded" };
}
}The key rule is one-way dependency: the domain owns the interface; the adapter depends outward on the vendor details. Never let stripe.PaymentIntent types leak through checkout logic if Stripe is merely an implementation detail.
Facade: present a smaller surface
A facade provides a simpler entry point over a subsystem. This is useful when consumers need two common operations but the subsystem exposes forty knobs. The danger is a facade becoming a god object that absorbs unrelated responsibilities. Keep it as an interface over a workflow, not a junk drawer for every helper.
Decorator: add behavior without editing the core
Decorators compose cross-cutting behavior: retries, caching, logging, authorization.
class RetryNotifier:
def __init__(self, inner: Notifier, attempts: int = 3):
self.inner = inner
self.attempts = attempts
def send(self, message: str) -> None:
for attempt in range(self.attempts):
try:
return self.inner.send(message)
except TransientError:
if attempt == self.attempts - 1:
raiseThis works because the wrapper honors the same contract as the wrapped object. If callers must know whether retries exist, composition has leaked.
Strategy and command: replace branching with named decisions
Strategy isolates interchangeable algorithms; Command packages an operation with its inputs so it can be queued, logged, undone, or retried. They are excellent when variation is real. They are painful when every if statement becomes a class hierarchy.
Observer: decouple producers and consumers
Events are powerful when downstream work is genuinely optional or extensible. They are dangerous when correctness depends on invisible listeners. Prefer explicit calls for required workflows; use observers for telemetry, cache invalidation, webhooks, and other extensible side effects.
Field notes
- Indirection should pay rent: testing, substitution, isolation, or independent evolution.
- Required behavior hidden behind events is operationally fragile and hard to trace.
- Structural patterns should simplify the caller's view, not merely satisfy an architecture diagram.
Was this lesson helpful?