Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 57 ยท Practice and Interview Prep

Design Patterns Cheat Sheet

A one-page design patterns cheat sheet: intent, when to use, structure, pitfalls and language idioms for every GoF pattern plus SOLID and a pattern picker.

This page is a quick reference for the whole track. It lists every pattern from the course in one place with its intent, when to reach for it, how it is built and what goes wrong. It ends with a SOLID summary, a "which pattern for which problem" chooser, and the idioms that make some patterns almost disappear in modern languages.

Use it as a review after finishing the lessons, or as a lookup during design work. Each pattern name links to its full lesson. A cheat sheet cannot teach a pattern from zero. If a row feels cryptic, open the lesson. And remember the rule from What Are Design Patterns?: choose a pattern because a problem asks for it, never because it is on a list.

Three families

Creational How objects get made.
Structural How objects fit together.
Behavioral How objects cooperate.
1 / 2

Creational patterns

Pattern Intent Use when Structure Watch out for
Singleton One instance, one access point Exactly one shared resource (config, registry) Private constructor plus static accessor, or a module-level object Hidden global state, hard tests, thread safety
Factory Method Let a creator decide which product to build Code should not name concrete classes Creator with a create() method; subclasses or a registry return products A factory with a giant switch has not solved anything
Abstract Factory Create families of matching products Products must be used together (light or dark widgets) Factory interface with several createX() methods; one factory per family Adding a new product type changes every factory
Builder Build a complex object step by step Many optional parts, validation, immutability Builder with setters returning this and a build() that validates Mutable builders reused by mistake
Prototype Create objects by copying a template Construction is costly or configuration-heavy clone() method, often with a registry of templates Shallow copies sharing nested state
Object Pool Reuse expensive objects Connections, threads, buffers Pool with acquire() and release() Stale state, leaks, pooling cheap objects

Structural patterns

Pattern Intent Use when Structure Watch out for
Adapter Make an existing interface fit another Integrating legacy or third-party code Wrapper implementing the target interface, calling the adaptee Too many adapters hide a poor boundary
Bridge Separate an abstraction from its implementation Two dimensions vary (shape and renderer) Abstraction holds a reference to an implementor interface Overkill for one dimension
Composite Treat one and many uniformly Tree structures (files, menus, UI) Component interface, leaf and composite with children Leaf methods that make no sense (add on a leaf)
Decorator Add behavior by wrapping Optional features that combine freely Wrapper with the same interface as the wrapped object Many small wrappers are hard to debug; order matters
Facade Simplify a subsystem A complex library or subsystem needs a friendly entry One class exposing a few high-level methods Becoming a god class
Flyweight Share state to save memory Huge numbers of similar objects Factory returning shared intrinsic objects; extrinsic data passed in Complexity for small savings
Proxy Control access to an object Lazy loading, permissions, caching, remote calls Stand-in with the same interface that forwards to the real subject Hidden latency or side effects

Behavioral patterns

Pattern Intent Use when Structure Watch out for
Strategy Swap algorithms Several ways to do one job, chosen at run time Interface plus interchangeable implementations held by a context Too many tiny classes where a function would do
Observer Notify dependents of a change One event, many listeners Subject with subscribe, unsubscribe and notify Forgotten unsubscribes leak memory; update storms
Command Turn a request into an object Undo, queues, logging, macros Command with execute (and undo), an invoker, a receiver Undo of side effects outside the model
State Behavior changes with status Life cycles, workflows, machines Context delegates to a state object that picks the next state Many states with many transitions need a table or diagram
Template Method Fixed skeleton, variable steps Same algorithm with a few differing steps Base class method calling overridable hooks Deep inheritance, fragile base classes
Iterator Traverse without exposing structure Custom collections, lazy sequences next/hasNext, __iter__, generators Modifying a collection while iterating
Chain of Responsibility Pass a request along handlers Middleware, approvals, filters Handlers each decide to handle or forward A request nobody handles; hard-to-trace order
Mediator Centralize communication Many components talk to many Mediator object that components call instead of each other The mediator turns into a god object
Memento Save and restore state Undo, checkpoints Immutable snapshot created and restored by the originator Memory use of many snapshots
Visitor Add operations to a hierarchy Stable classes, growing operations (compilers, exporters) accept(visitor) and one visit method per element type Adding an element type breaks all visitors
Interpreter Evaluate a small language Rules, expressions, simple DSLs One class per grammar rule, interpret(context) Does not scale to large grammars
Null Object Replace null with a harmless object Callers keep checking for null Do-nothing implementation of the interface Hiding real errors that should fail

Architectural and modern patterns

Pattern Intent Use when Watch out for
Repository Hide persistence behind a collection-like interface Domain logic should not know SQL Leaky abstractions, one method per query
Unit of Work Track changes and commit them together Several changes must succeed or fail as one Long-lived units hold memory
MVC / MVP / MVVM Separate presentation from logic Any UI with logic worth testing Fat controllers or view models
Dependency Injection Pass dependencies in Testability, swappable parts Service locators hide dependencies
Plugin registry Extend by registering modules Third-party or optional features Unclear load order and versioning

The rest of the picture

SOLID in one table

Letter Principle One-line test Patterns that help
S Single Responsibility Can you describe the class without the word "and"? Facade, Strategy, Repository
O Open/Closed Can you add a case without editing existing code? Strategy, Decorator, Factory
L Liskov Substitution Does the subtype keep every promise of the base? Composition instead of bad inheritance
I Interface Segregation Does anyone implement methods they never use? Role interfaces, Adapter
D Dependency Inversion Does high-level code import a concrete low-level class? DI, Factory, Repository

Related rules from DRY, KISS, YAGNI and More: do not duplicate knowledge, keep it simple, build only what is needed, talk only to your neighbors, and prefer composition over inheritance.

Which problem, which pattern?

If you see... Think about...
A growing if/else or switch on a type or mode Strategy, State, Factory or polymorphism
new ConcreteClass() scattered through the code Factory Method, Abstract Factory or dependency injection
A constructor with ten parameters Builder
Behavior that depends on a status field State
A class that knows too much about a library Adapter or Facade
Needing optional features that combine Decorator
Trees of things treated alike Composite
"Notify everyone who cares" Observer
Undo, redo, queue or replay Command (plus Memento)
Several handlers and unclear who should act Chain of Responsibility
Many components calling each other Mediator
Operations growing on a stable class hierarchy Visitor
Null checks everywhere Null Object
Slow or remote object accessed directly Proxy

Language idioms

Many patterns are language features in disguise. Before building the full class structure, check whether your language already gives you the idea.

Pattern JavaScript Python Java / C++
Singleton Module-level object Module-level object Enum singleton (Java), function-local static (C++)
Strategy Pass a function Pass a callable Functional interface / std::function
Command Closure Callable object Runnable / lambda
Iterator Generator function* Generator or __iter__ Iterable / range-based for
Decorator Higher-order function @decorator syntax Wrapper class
Observer EventTarget, emitters Callbacks, signals Listener interfaces
Template Method Higher-order function Higher-order function Abstract base class
Builder Options object Keyword arguments Builder class
Prototype structuredClone copy.deepcopy Copy constructor / clone()

Patterns Across Languages explains the reasons behind this table.

Two runnable helpers

The first helper is a small pattern picker. It matches words in a problem description against keywords for each pattern. It is only a toy (real design needs judgment), but writing down the keywords for each pattern is a useful way to learn the "smell" that leads to it.

JS A toy pattern picker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second helper shows the idioms from the table above: five patterns written as a few lines of JavaScript, with no class hierarchy at all.

JS Patterns as language features

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Using the cheat sheet well

  • Start from the problem column, not the name. Find the symptom, read the pattern's pitfall, then open the lesson.
  • Combine, but sparingly. Factory plus Strategy and Decorator plus Composite are common pairs; three or more patterns in one small class are a warning.
  • Check the idiom column before writing a class hierarchy.
  • Revisit the pitfalls during code review. Most pattern misuse is one of: unnecessary indirection, hidden global state, a mediator or facade that grew too big, or inheritance where composition would do.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class has a constructor with ten parameters, most optional. Which pattern is the best first candidate?

    Builder constructs complex objects step by step, validates in build() and avoids telescoping constructors.
  2. 2. Which pair of patterns both wrap an object while keeping its interface?

    Decorator and Proxy keep the wrapped object's interface; the difference is intent: add behavior versus control access.
  3. 3. Adding a new element type forces a change in every existing visitor. Which pattern has this trade-off?

    Visitor makes new operations easy and new element types expensive. The opposite holds for ordinary polymorphism.
  4. 4. In JavaScript, which language feature most directly replaces a full Iterator class?

    A generator function produces a lazy sequence and implements the iterator protocol for you.
  5. 5. Which SOLID principle does 'high-level code imports a concrete low-level class' violate?

    High-level modules should depend on abstractions that low-level modules implement.

Summary

  • Creational patterns control object creation, structural patterns control composition, and behavioral patterns control cooperation.
  • Pick a pattern from the problem you can name, then check its pitfall column before committing.
  • The pairs worth memorizing: Strategy versus State, Adapter versus Facade, Decorator versus Proxy, Factory Method versus Abstract Factory.
  • SOLID explains why most patterns exist: Open/Closed and Dependency Inversion drive Strategy, Factory, Decorator and DI.
  • In modern languages many patterns are a function, closure, module or generator; use the idiom first.
  • Keep designs small. A pattern earns its place only when it removes a real problem.

This is the last page of the Design Patterns and OOP Design track. A good next step is to revisit How to Approach a Low-Level Design Problem and apply the whole toolkit to a problem of your own.