From Refactoring.Guru — design patterns explained with real-world analogies and code in C++, JavaScript & TypeScript. Also includes architectural patterns and 35 system design case studies.
A design pattern is a general, reusable solution to a commonly occurring problem in software design. It's not a finished piece of code — it's a template for how to solve a problem that can be adapted to different situations. Patterns formalize best practices so developers can communicate solutions using a shared vocabulary.
Instead of re-inventing architectures for every project, you recognize the problem, recall the applicable pattern, and apply its proven structure.
How to make objects without making a mess.
| Pattern | What It Does | Real-World Analogy |
|---|---|---|
| Factory Method | Defines an interface for creating objects, letting subclasses decide which class to instantiate | A logistics company that dispatches either trucks or ships depending on the route — the caller doesn't control the vehicle type |
| Abstract Factory | Produces families of related objects without specifying their concrete classes | A furniture catalog organized by style: choosing "Modern" gives you a matching chair, sofa, and table — no mixing across styles |
| Builder | Constructs complex objects step by step, allowing different representations from the same construction process | A sandwich assembly line: bread, protein, toppings, sauce — the steps are fixed, but each builder produces a different sandwich |
| Prototype | Creates new objects by copying an existing object (the prototype) | A document template system: you duplicate a master document and fill in the fields rather than building from scratch each time |
| Singleton | Ensures a class has only one instance with a global access point | A database connection pool shared across the entire application — every module talks to the same pool manager |
How to put objects together into bigger structures.
| Pattern | What It Does | Real-World Analogy |
|---|---|---|
| Adapter | Allows objects with incompatible interfaces to collaborate | A power plug adapter — a US plug won't fit a European socket, but the adapter bridges the mismatch without modifying either end |
| Bridge | Decouples an abstraction from its implementation so both can evolve independently | A universal remote control that works with any TV brand — change the remote or the TV without affecting the other |
| Composite | Composes objects into tree structures and lets clients treat individuals and compositions uniformly | A file system where both a single file and a directory full of nested subdirectories support the same size() operation |
| Decorator | Attaches new responsibilities to objects dynamically by wrapping them | Adding optional features to a coffee order — milk, sugar, whipped cream — without changing the coffee class itself |
| Facade | Provides a simplified interface to a complex subsystem | A single "compile" button in an IDE that invokes the lexer, parser, optimizer, and code generator behind the scenes |
| Flyweight | Reduces memory usage by sharing common state across many objects | A text editor reusing glyph objects — the letter 'A' shape is stored once and referenced by every 'A' in the document |
| Proxy | Provides a surrogate or placeholder to control access to another object | A lazy-loading image proxy — a placeholder is shown immediately while the full-resolution image loads in the background |
How objects communicate and cooperate.
| Pattern | What It Does | Real-World Analogy |
|---|---|---|
| Chain of Responsibility | Passes a request along a chain of handlers until one handles it | A customer support ticket that escalates from Level 1 to Level 2 to management until someone can resolve it |
| Command | Encapsulates a request as an object, allowing parameterization, queuing, and undo | An order at a restaurant: the waiter writes a ticket (command) that decouples the customer request from the kitchen's execution |
| Iterator | Provides a way to access elements of a collection sequentially without exposing its underlying structure | A playlist player with next() and previous() — you traverse songs regardless of whether they're stored in an array, linked list, or database |
| Mediator | Centralizes complex communication between objects to reduce coupling | An air traffic controller — planes don't talk to each other directly; the controller coordinates all landings and takeoffs |
| Memento | Captures and externalizes an object's internal state so it can be restored later | A text editor's undo system — it stores snapshots of the document state that can be restored at any point |
| Observer | Defines a one-to-many dependency so that when one object changes state, all dependents are notified | A publish-subscribe system: YouTube notifies all subscribers when a new video is uploaded — the creator never calls each subscriber individually |
| State | Allows an object to alter its behavior when its internal state changes | A network connection: a Connection object behaves differently in Connecting, Connected, and Disconnected states without conditional branches |
| Strategy | Defines a family of interchangeable algorithms and makes them swappable at runtime | A payment processor that supports credit card, PayPal, and cryptocurrency — the checkout flow stays the same, the payment method is pluggable |
| Template Method | Defines the skeleton of an algorithm, letting subclasses fill in specific steps | A data migration pipeline: extract → transform → load is fixed, but each database type implements the steps differently |
| Visitor | Lets you define new operations on a set of objects without changing the objects themselves | A code linter that walks every node of an AST — add a new lint rule without modifying any of the AST node classes |
How to design large-scale, distributed, and resilient systems.
| Pattern | What It Does | Real-World Analogy |
|---|---|---|
| CQRS | Separates read and write operations into different models so each can be optimized independently | A library with separate desks for check-out (commands) and catalog search (queries) |
| Event Sourcing | Stores state changes as an append-only log of events; current state is derived by replaying them | A bank statement stores every deposit and withdrawal — your balance is computed by replaying all transactions |
| Saga | Manages distributed transactions as a sequence of local steps, each with a compensating action for rollback | Booking a trip: reserve flight, then hotel, then car — if the car fails, cancel the hotel and flight |
| Circuit Breaker | Detects repeated failures and temporarily stops calls to a service, giving it time to recover | An electrical breaker trips when it detects a fault, then resets after a cooldown |
| Bulkhead | Isolates resources into separate pools so a failure in one partition doesn't cascade | A ship's watertight compartments — one flooded compartment doesn't sink the whole ship |
| Sidecar | Deploys a helper process alongside the main application to handle cross-cutting concerns | A motorcycle sidecar adds cargo capacity without modifying the motorcycle itself |
| Ambassador | Creates an outbound proxy that handles retries, auth, metrics, and circuit breaking on behalf of a client | A diplomatic ambassador handles communication protocols so the home government doesn't have to |
Real-world systems that demonstrate how design patterns compose into production architectures. Each case study includes requirements, class diagrams (Mermaid), design pattern analysis, working code in C++, JavaScript, TypeScript, and sequence diagrams.
| Case Study | Description | Key Patterns Used |
|---|---|---|
| WhatsApp / Messenger | Real-time messaging with 1-on-1/group chats, presence, delivery status, encryption, cross-device sync | Mediator, Observer, State, Command, Proxy, Chain of Responsibility |
| Uber / Ride Sharing | Rider-driver matching, real-time GPS, fare calculation, surge pricing, trip lifecycle | Strategy, State, Observer, Mediator, Command, Facade |
| YouTube / Video Streaming | Video upload/transcoding, adaptive streaming, subscriptions, comments, recommendations | Strategy, State, Proxy, Observer, Command, Facade |
| Twitter Feed / Social Media | Timeline generation, follows, retweets, likes, hashtags, trending, fan-out architecture | Strategy, Observer, Chain of Responsibility, Command, Iterator, Flyweight |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Google Docs | Real-time collaborative editing, cursor presence, version history, operational transforms | Command, Memento, Observer, Mediator, Proxy |
| Dropbox / File Sync | File sync/sharing, conflict resolution, delta sync, versioning, folder permissions | Command, Strategy, State, Observer, Memento, Singleton |
| Airport Management | Flight scheduling, gate/runway assignment, check-in, baggage tracking, ATC | Mediator, Observer, State, Command, Facade, Singleton |
| Amazon / E-Commerce | Product catalog, cart, checkout, payment, inventory, shipping, notifications, reviews | Strategy, State, Observer, Decorator, Command, Facade, Singleton |
| Spotify / Music Streaming | Music catalog, playlists, free/premium playback, recommendations, offline downloads | Strategy, Proxy, Flyweight, Command, Iterator, Observer, Singleton |
| Netflix / Video Streaming | Content catalog, profiles, adaptive streaming, recommendations, watch history, My List | Strategy, State, Proxy, Observer, Command, Facade, Singleton |
| Parking Lot | Multi-floor parking with spot types, ticketing, pricing, and display boards | Singleton, Strategy, Observer, State, Factory Method |
| Sudoku | Board validation, solving (backtracking + constraint propagation), puzzle generation, hints | Strategy, Command, Memento, Observer, Template Method |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Rate Limiter | Token bucket, sliding window, burst handling, distributed rate limiting | Strategy, Decorator, Singleton, Factory Method |
| URL Shortener | Short URL generation, redirect, custom aliases, click analytics, expiration | Proxy, Strategy, Command, Observer, Singleton |
| Distributed Cache | Key-value store with TTL, LRU/LFU eviction, consistent hashing, replication | Strategy, Proxy, Flyweight, Singleton, Chain of Responsibility |
| Message Queue | Pub-sub, consumer groups, delivery guarantees, offset tracking, dead letter queues | Observer, Strategy, Template Method, Command, Chain of Responsibility, Iterator, Memento |
| API Gateway | Request routing, auth, rate limiting, circuit breaker, service discovery, load balancing | Facade, Chain of Responsibility, Strategy, Decorator, Proxy, Command |
| CDN / Content Delivery | Global edge caching, geo-routing, cache invalidation, origin pull/push, DDoS protection | Proxy, Strategy, Observer, Facade, Flyweight, Singleton |
| Load Balancer | Request distribution across servers, health checking, sticky sessions, connection draining | Strategy, Observer, Decorator, Proxy, Command, Facade |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Git / Version Control | Distributed VCS with commits, branching/merging, staging, diff, reflog, garbage collection | Memento, Command, Composite, Iterator, Strategy, Prototype, Visitor |
| Docker / Container Runtime | Container engine with image layering, namespace isolation, cgroups, registry, networking | Builder, Composite, Prototype, Strategy, Command, Proxy, Singleton |
| SQL Database Internals | Relational DB with B-tree indexing, MVCC, WAL, query planning, joins, replication | Strategy, Command, Template Method, Iterator, Memento, Flyweight, Proxy, Composite |
| Web Crawler | Distributed crawling with politeness, dedup, robots.txt, rate limiting, recrawl scheduling | Strategy, Template Method, Chain of Responsibility, Command, State, Iterator, Singleton |
| Search Engine | Google-like search with inverted index, TF-IDF/BM25/PageRank, query parsing, snippets | Strategy, Template Method, Composite, Iterator, Memento, Flyweight, Singleton |
Modern AI-powered systems using LLMs, vector databases, RAG pipelines, embeddings, and agent architectures.
| Case Study | Description | Key Patterns Used |
|---|---|---|
| ChatGPT / LLM Service | Multi-turn LLM serving, streaming, RAG pipeline, model routing, content moderation, conversation export | Strategy, Observer, Chain of Responsibility, Decorator, Memento, Proxy, Command, Singleton |
| RAG Search Engine | Perplexity-like AI search with hybrid vector+keyword search, document ingestion, citation synthesis | Strategy, Template Method, Facade, Observer, Chain of Responsibility, Decorator, Singleton |
| AI Agent Memory | Episodic/semantic/working memory, memory consolidation, multi-agent shared memory, knowledge graph | Strategy, Memento, Observer, Command, Flyweight, Template Method, Singleton |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Multi-Model AI Gateway | Route to cheapest/fastest LLM, fallback chains, cost tracking, A/B testing, prompt templating | Strategy, Chain of Responsibility, Template Method, Decorator, Facade, Observer, Proxy, Singleton |
| Code Search Engine | Sourcegraph-like semantic code search, AST parsing, embeddings, cross-repo navigation | Visitor, Strategy, Template Method, Flyweight, Composite, Command, Proxy, Singleton |
| Document Assistant | Notion AI-like document Q&A, multi-format ingestion, RAG with citations, document comparison | Strategy, Template Method, Facade, Observer, Decorator, Chain of Responsibility, Singleton |
| AI Observability & Evals | LLM tracing, eval suites, hallucination detection, drift monitoring, regression testing, alerting | Strategy, Template Method, Observer, Decorator, Chain of Responsibility, Memento, Singleton |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Prompt Injection Guard | Multi-layer defense against prompt injection, jailbreaks, PII leakage, with audit logging | Chain of Responsibility, Strategy, Decorator, Observer, Memento, Command, Singleton |
| AI Compliance & Governance | Regulatory compliance (EU AI Act, SOC 2), bias detection, explainability, model cards, audit trails | Strategy, Template Method, Command, Memento, Observer, Decorator, Chain of Responsibility, Singleton |
| Case Study | Description | Key Patterns Used |
|---|---|---|
| Recommendation Engine | ML-powered recommendations with embeddings, ANN search, hybrid filtering, A/B testing, cold start | Strategy, Decorator, Observer, Template Method, Flyweight, Facade, Singleton |
| Enterprise Support Bot | RAG support with multi-source KB, ticket escalation, sentiment detection, SLA tracking | Strategy, Chain of Responsibility, Template Method, Observer, State, Command, Proxy, Facade, Singleton |
A comprehensive cross-reference table maps every design pattern to every system design that uses it — useful for finding which patterns solve which real-world problems.
creational/ — 5 patterns (object creation)
structural/ — 7 patterns (object composition)
behavioral/ — 10 patterns (object communication)
architectural/ — 7 patterns (enterprise & distributed systems)
system-design/
├── classic/ — 24 case studies (real-world systems)
└── ai-systems/ — 11 case studies (AI/ML/modern systems)
Each pattern file (creational, structural, behavioral, architectural) has:
- Intent — the problem it solves
- Analogy — a real-world comparison to ground the concept
- Structure — the classes and relationships involved
- C++ example — modern C++ (C++17)
- JavaScript example — ES6+ class syntax
- TypeScript example — typed with interfaces
Each system design case study has:
- Requirements — functional and non-functional
- Class diagram — Mermaid diagram showing all entities and patterns
- Design patterns used — which patterns apply and where
- Implementation — working code in C++, JavaScript, TypeScript
- Sequence diagram — Mermaid showing the key runtime flows
- Extensibility — how to add new features
All pattern content based on Refactoring.Guru by Alexander Shvets.