When a single bottleneck threatens end-to-end availability, Decorator, Factory & Observer, reach for patterns to isolate a concrete axis of change (varying pricing rules, composable I/O streams, multi-channel alerts), never as preemptive ceremony around static code.
TL;DR30-second simplified summary▾
Core Mechanics: Rather than hardcoding how an operation runs, what concrete class is built, or who reacts to state changes, these four GoF patterns favor composition over deep inheritance: Factory: Centralizes conditional instantiation behind a creation seam.
Visual & Structural Flow: Depicts Factory + Decorator + Strategy + Observer in Order Notification (PaymentService -> AlertObserver -> NotifierFactory -> Decorator Stack); Factory-Assembled Decorator & Strategy Object Graph (NotifierFactory -> RateLimitedNotifier -> RetryingNotifier -> WhatsApp + Strategy).
Trade-Offs & Production: Match the pattern to the exact axis of change. Keep decorator stacks <=3–4 layers and log layer names on failure.
Failure Modes & Application: Apply GoF patterns in real LLD problems and see how they pair with Dependency Injection and SOLID.
What are Strategy, Decorator, Factory & Observer.
Why this matters: The mechanism: understand how Strategy, Decorator, Factory & Observer works from first principles.
Rather than hardcoding how an operation runs, what concrete class is built, or who reacts to state changes, these four GoF patterns favor composition over deep inheritance:
- Factory: Centralizes conditional instantiation behind a creation seam.
- Strategy: Encapsulates interchangeable algorithms behind a shared interface.
- Decorator: Wraps an object implementing the same interface (
O(N)composable layers instead ofO(2^N)subclasses). - Observer: Defines a 1-to-many in-process publish-subscribe contract.
Why Polymorphic Seams Beat Copy-Pasted `if/else` & Subclass Explosion.
Why this matters: The problem: see what breaks without Why Polymorphic Seams Beat Copy-Pasted if/else & Subclass Explosion under real concurrency or scale.
Think of Why Polymorphic Seams Beat Copy-Pasted if/else & Subclass Explosion as the intuition layer for GoF Design Patterns: Strategy, Decorator, Factory & Observer: The problem: see what breaks without Why Polymorphic Seams Beat Copy-Pasted if/else & Subclass Explosion under real concurrency or scale.
Without these four patterns, teams duplicate if/else branches across billing/routing modules or build combinatorial subclasses (EncryptedCompressedBufferedStream). Composing Factory -> Decorator Stack -> Strategy keeps core domain workflows untouched when new channels or pricing tiers arrive.
Factory + Decorator + Strategy + Observer in Order Notification
Factory enforces canonical Decorator ordering, Strategy formats the payload, and Observer decouples PaymentService from notifications.
- Problem
- How to implement GoF Design Patterns: Strategy, Decorator, Factory & Observer without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When a single bottleneck threatens end-to-end availability, decorator, Factory & Observer, reach for patterns to isolate a concrete axis of change (varying pricing rules, composable I/O streams, multi-channel alerts), never as preemptive ceremony around static code.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When GoF Design Patterns: Strategy, Decorator, Factory & Observer experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Composable HTTP Client Middleware via Decorator
Wrapping HttpClient in RetryingClient(MetricsClient(AuthClient(OkHttpTransport))) lets each concern be unit-tested in isolation and toggled per partner.
Dynamic Freight & Surge Pricing via Strategy + Factory
Mapping (tier, city) to a stateless PricingStrategy meant adding a new festive-surge rule took one new class and zero edits to QuoteService.
Where GoF Patterns Fit (and When Plain Language Idioms Win).
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Where GoF Patterns Fit (and When Plain Language Idioms Win) as the intuition layer for GoF Design Patterns: Strategy, Decorator, Factory & Observer: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Follow the Rule of Three: write direct code first, and extract Strategy/Factory only when a second or third genuine variant arrives.
| Choice | What it buys | What it costs |
|---|---|---|
| Use: Runtime Algorithm Swaps & Composable I/O | Cleanly isolates payment fee rules, rerankers, or retry/metrics/auth transport wrappers. | Deeper stack traces; 4 layers of interfaces can obscure IDE navigation. |
| Prefer Idioms: First-Class Functions & `sealed interface` | Python `dict[str, Callable]` / `@retry` or Java 21 `sealed interface` + `switch` eliminates 5 boilerplate subclasses. | N/A—modern idioms are strictly cleaner for single-method strategies. |
| Avoid: In-Process Observer for Cross-Service Reliability | Use Transactional Outbox + Kafka/SQS when delivery must survive process restarts. | In-memory listeners leak memory if never unsubscribed and drop events on crash. |
How to Prevent Decorator Ordering, Stateful Strategy & Leak Bugs.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
1.
Enforce Decorator Order in a Factory: Gzip(Encrypt(stream)) compresses high-entropy ciphertext and inflates size—always assemble wrappers in a Factory (Encrypt -> Compress -> Buffer). 2. Keep Strategies Stateless: Never store per-request fields on singleton Strategy beans.
How to Prevent Decorator Ordering, Stateful Strategy & Leak Bugs
# Stateless Strategy registry + Factory-ordered Decorator composition (Python)
from typing import Callable, Protocol
class Notifier(Protocol):
def send(self, msg: str) -> None:...
class RetryingNotifier:
def __init__(self, inner: Notifier, attempts: int = 3): # Canonical wrapper
self._inner, self._attempts = inner, attempts
def send(self, msg: str) -> None:
for i in range(self._attempts):
try: return self._inner.send(msg)
except TimeoutError:
if i == self._attempts - 1: raise
FORMATTERS: dict[str, Callable[[str], str]] = {
'sms': lambda m: m[:160],
'whatsapp': lambda m: f'*[Alert]* {m}',
}
Alternatives: Pattern Selection Matrix.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: Pattern Selection Matrix as the intuition layer for GoF Design Patterns: Strategy, Decorator, Factory & Observer: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Match the pattern to the exact axis of change.
Alternatives: Pattern Selection Matrix
| Choice | What it buys | What it costs |
|---|---|---|
| Strategy (`Comparator<T>`, `Callable`) | Swaps algorithms at runtime without branching in host code. | Overkill for 2 stable branches. |
| Decorator (`BufferedReader(InputStreamReader(in))`) | Stacks orthogonal behaviors dynamically at runtime. | Type system doesn't catch wrapper ordering bugs. |
| Factory (`List.of()`, self-registering map) | Hides concrete types and enforces valid decorator stacking. | Large `switch` factories rot unless backed by a registration map. |
| Observer (`ApplicationEventPublisher`) | Zero infra overhead for in-process UI/cache invalidation. | Slow listeners block the publisher unless offloaded to bounded async executors. |
Production Architecture: Bounded Async Observer & Safe Decorator Stack.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Production Architecture: Bounded Async Observer & Safe Decorator Stack as the intuition layer for GoF Design Patterns: Strategy, Decorator, Factory & Observer: Production architecture: see how the components compose end to end under real load.
Keep decorator stacks <=3–4 layers and log layer names on failure. Isolate non-critical Observers onto bounded async executors with timeouts (or move them to an Outbox/Kafka topic) so a slow analytics listener never stalls checkout latency.
Factory-Assembled Decorator & Strategy Object Graph
Centralizing decorator assembly in a Factory prevents callers from accidentally inverting rate-limit, retry, or compression layers.
Problems solved & Related Concepts.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of Problems solved & Related Concepts as the intuition layer for GoF Design Patterns: Strategy, Decorator, Factory & Observer: Applied problems: connect these internals to concrete system design and debugging scenarios.
Apply GoF patterns in real LLD problems and see how they pair with Dependency Injection and SOLID.
Practice: Make the trade-off yourself.
A team wraps an I/O stream as `GzipDecorator(EncryptDecorator(fileStream))`, and compressed file sizes *increase* instead of shrinking. Why?