Skip to main content
← CONCEPTS / SOFTWARE DESIGN & ARCHITECTURE
An end-to-end domain learning journey

GoF Design Patterns: Strategy,
Decorator, Factory & Observer.

The Gang of Four (GoF) patterns—especially Strategy, Decorator, Factory, and Observer—provide battle-tested structural templates for swapping algorithms, layering cross-cutting behavior, encapsulating object creation, and decoupling event producers from consumers.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
PRIME Core Invariants & Workload Constraints
Establish concrete scale, latency, memory, and concurrency bounds for GoF Design Patterns: Strategy, Decorator, Factory & Observer before selecting data structures or storage components.
Failure Boundaries & Operational Trade-Offs
Identify hot-key skew, partial failures, resource leaks, and when simpler single-node or standard alternatives outperform complex designs.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

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 of O(2^N) subclasses).
  • Observer: Defines a 1-to-many in-process publish-subscribe contract.
02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

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.

Pattern Composition

Factory + Decorator + Strategy + Observer in Order Notification

PaymentServiceAlertObserverNotifierFactoryDecorator Stack1. Emit InvoicePaidEvent(decoupled)2. forChannel(WHATSAPP)3. RateLimit(Retry(WhatsApp(Fmt)))4. Strategy formats + retries send

Factory enforces canonical Decorator ordering, Strategy formats the payload, and Observer decouples PaymentService from notifications.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

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.

ChoiceWhat it buysWhat it costs
Use: Runtime Algorithm Swaps & Composable I/OCleanly 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 ReliabilityUse Transactional Outbox + Kafka/SQS when delivery must survive process restarts.In-memory listeners leak memory if never unsubscribed and drop events on crash.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

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.

Component Topology

How to Prevent Decorator Ordering, Stateful Strategy & Leak Bugs

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
# 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}',
}
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

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.

Lifecycle & Failure Recovery

Alternatives: Pattern Selection Matrix

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
ChoiceWhat it buysWhat 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.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

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.

Composition Hierarchy

Factory-Assembled Decorator & Strategy Object Graph

NotifierFactoryEnforces canonical orderRateLimitedNotifierRetryingNotifierPage 0WhatsApPage 2Page 3

Centralizing decorator assembly in a Factory prevents callers from accidentally inverting rate-limit, retry, or compression layers.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

A team wraps an I/O stream as `GzipDecorator(EncryptDecorator(fileStream))`, and compressed file sizes *increase* instead of shrinking. Why?

Recommended Learning Flow