Design Patterns Quick Reference
Master the essentials
Creational Patterns
Singleton Pattern
Office Printer
Like an office with one shared printer that everyone uses instead of buying individual printers.
Ensures only one instance of a class exists throughout the application – everyone shares the same resource.
- One shared instance
- Global access point
- Lazy or eager initialization
- Thread-safe implementation
Factory Method Pattern
Payment Gateways
Like choosing a payment method at checkout: credit card, PayPal, or crypto, each processed differently.
Defines an interface for creating objects, but lets subclasses decide which class to instantiate.
- Defers object creation to subclasses
- Promotes loose coupling
- Easy to extend with new types
- Single Responsibility Principle
Abstract Factory Pattern
BMW X3 Trim Lines
Like a BMW factory assembling Core, M Sport, and Luxury X3 trims, each with matching sets of parts.
Creates families of related objects without specifying their concrete classes – ensures components are compatible.
- Creates families of related objects
- Enforces compatibility
- Easy to swap product families
- Encapsulates object creation
Prototype Pattern
Copying a Slide Template
Like duplicating a presentation slide with the same layout; it's faster than designing from scratch.
Creates new objects by cloning existing ones – avoids expensive initialization or complex setup.
- Clone existing objects
- Avoids complex setup
- Runtime object creation
- Reduces initialization overhead
Builder Pattern
Building a House
Like a builder following steps to construct different houses: same process, different configurations.
Constructs complex objects step by step – separates construction from representation.
- Step-by-step construction
- Same process, different results
- Avoids telescoping constructors
- Fluent interface support
Structural Patterns
Adapter Pattern
Power Plug Adapter
Like a travel plug adapter converting a UK plug to fit a European socket, making incompatible things work together.
Converts the interface of a class into another interface clients expect – allows incompatible interfaces to work together.
- Connects incompatible interfaces
- Wraps existing class
- Reuses existing code
- Protects from third-party changes
Bridge Pattern
TV Remote and TVs
Like a universal remote working with different TV brands, where abstraction and implementation vary independently.
Separates abstraction from implementation so they can change independently – uses composition over inheritance.
- Decouples abstraction from implementation
- Both can vary independently
- Reduces class explosion
- Runtime binding
Composite Pattern
Folders and Files
Like folders containing files and other folders, treating individual items and groups uniformly.
Composes objects into tree structures – treats individual objects and compositions uniformly.
- Tree structure representation
- Uniform treatment of parts and whole
- Recursive composition
- Simplifies client code
Decorator Pattern
Gift Wrapping
Like adding gift wrap, ribbon, and a card to a present, adding features without changing the gift itself.
Adds responsibilities to objects dynamically – an alternative to subclassing for extending functionality.
- Adds behavior at runtime
- Wraps existing objects
- Flexible alternative to inheritance
- Follows Open-Closed Principle
Facade Pattern
Smart Home App
Like a smart home app controlling lights, heating, and security through one simple interface.
Provides a simplified interface to a complex subsystem – hides complexity behind a unified interface.
- Simplifies complex systems
- Unified interface
- Reduces coupling
- Easier to use and test
Flyweight Pattern
Airline Seat Map
Like sharing seat type objects (economy, business) across thousands of seats to save memory.
Shares common state between multiple objects to save memory – separates intrinsic from extrinsic state.
- Reduces memory usage
- Shares immutable state
- Separates intrinsic/extrinsic data
- Useful for large object counts
Proxy Pattern
Proxy Server
Like a proxy server controlling internet access by adding security, caching, or logging before reaching the real server.
Provides a surrogate or placeholder for another object – controls access to the original object.
- Controls access to object
- Lazy initialization support
- Adds security or caching
- Same interface as real object
Behavioural Patterns
Chain of Responsibility Pattern
Leave Request Approval Chain
Like a leave request climbing from team lead to manager to HR, where each level approves or passes it along.
Passes a request along a chain of handlers – each handler decides to process or pass to the next handler.
- Decouples sender and receiver
- Dynamic handler chain
- Single responsibility per handler
- Flexible request processing
Command Pattern
Voice Assistant (Alexa, Siri)
Like voice commands to Alexa, where each command encapsulates an action that can be queued, logged, or undone.
Encapsulates a request as an object – allows parameterization, queuing, logging, and undo operations.
- Encapsulates requests as objects
- Supports undo/redo
- Command queuing
- Decouples invoker from receiver
Interpreter Pattern
Language Translator
Like translating sentences word by word using grammar rules to interpret and evaluate expressions.
Defines grammar for a language and interprets sentences – used for scripting or expression evaluation.
- Defines language grammar
- Evaluates expressions
- Easy to change grammar
- Used in DSLs and parsers
Iterator Pattern
Elevator Stopping at Each Floor
Like an elevator stopping at each floor sequentially, providing a way to access elements without exposing the structure.
Provides sequential access to collection elements without exposing the underlying representation.
- Sequential access to elements
- Hides internal structure
- Multiple iterators simultaneously
- Uniform iteration interface
Mediator Pattern
Air Traffic Controller
Like an air traffic controller coordinating planes, centralizing communication instead of plane-to-plane chaos.
Centralizes communication between objects – reduces coupling by preventing direct object-to-object references.
- Centralizes communication
- Reduces object coupling
- Simplifies maintenance
- Reusable mediator logic
Memento Pattern
Game Save Feature
Like saving game progress, capturing and restoring object state without exposing internal details.
Captures and externalizes an object's internal state so it can be restored later without violating encapsulation.
- Saves object state
- Supports undo/restore
- Preserves encapsulation
- State history management
Observer Pattern
YouTube Subscriber
Like subscribing to a YouTube channel; you get notified automatically when new videos are uploaded.
Defines a one-to-many dependency – when one object changes, all dependents are notified automatically.
- Subscribe/publish mechanism
- Loose coupling between objects
- Automatic notification
- Dynamic subscription
State Pattern
Phone Modes: Silent, Vibrate, Normal
Like a phone responding differently in each mode with the same interface but different behavior based on state.
Changes object behavior when internal state changes – encapsulates state-specific logic in separate classes.
- State-specific behavior
- Eliminates conditionals
- Easy to add new states
- Cleaner state transitions
Strategy Pattern
Navigation App Routes
Like choosing the fastest, shortest, or scenic route in Google Maps: different algorithms for the same goal.
Defines a family of algorithms and makes them interchangeable – the algorithm varies independently from clients.
- Encapsulates algorithms
- Runtime algorithm selection
- Eliminates conditionals
- Easy to add new strategies
Template Method Pattern
Baking a Cake from a Recipe
Like following a recipe with fixed steps (prep, mix, bake, decorate), where each cake type customizes the details.
Defines the skeleton of an algorithm in a base class – lets subclasses override specific steps without changing structure.
- Defines algorithm structure
- Subclasses customize steps
- Code reuse in base class
- Hollywood Principle (Don't call us)
Visitor Pattern
Visitors at a Company Office
Like different visitors (delivery, client, inspector) performing different actions at the same office locations.
Separates algorithm from object structure – allows adding new operations without modifying existing classes.
- Separates operations from structure
- Easy to add new operations
- Double dispatch pattern
- Useful for complex object structures
Data Access Patterns
Repository Pattern
Library Catalogue
Like a library catalogue; you ask the librarian for books instead of searching the shelves yourself.
Abstracts data access logic – provides a collection-like interface for accessing domain objects.
- Abstracts data layer
- Centralized data access
- Testable without database
- Separation of concerns
Unit of Work Pattern
Supermarket Checkout
Like a shopping cart at checkout: collect all items, then pay for everything at once or cancel the whole order.
Maintains a list of objects affected by a transaction – coordinates writing changes to the database.
- Tracks changes in transaction
- Commits all or nothing
- Ensures data consistency
- Works with repositories
Data Mapper Pattern
Delivery Service
Like a delivery service moving goods between warehouse and store, translating storage format to display format.
Transfers data between objects and database – keeps domain model and database schema independent.
- Separates domain from database
- Translates between layers
- Domain model stays clean
- Complex mapping logic isolated
CQRS Pattern
Post Office Parcels
Like separate counters at the post office: one for sending parcels, another for tracking them.
Separates read and write operations – commands modify data, queries retrieve data.
- Separate read/write models
- Optimized for different purposes
- Scalability benefits
- Complex event sourcing integration
Specification Pattern
Club Entry Rules
Like club bouncers checking entry rules (age, dress code, guest list), combining rules as needed.
Encapsulates business rules as reusable objects – can combine specifications for complex queries.
- Business rules as objects
- Reusable and combinable
- Cleaner than scattered conditions
- And/Or/Not composition
Pipeline/Middleware Pattern
Assembly Line
Like a factory assembly line where each station processes the item and passes it to the next.
Processes requests through a series of handlers – each stage performs a specific operation.
- Sequential processing stages
- Single responsibility per stage
- Easy to add/remove stages
- Common in web frameworks
Architectural Patterns
MVVM Pattern
Restaurant Tablet Ordering System
Like a restaurant tablet system with View (tablet screen), ViewModel (logic), and Model (kitchen system).
Model-View-ViewModel architecture with two-way data binding – separates UI from business logic.
- Two-way data binding
- Testable ViewModel
- Reusable logic across Views
- Common in WPF and MAUI
MVC Pattern
Bank ATM
Like a bank ATM with Model (account data), View (screen), and Controller (processes actions).
Model-View-Controller architecture – separates data, presentation, and user input handling.
- Separates concerns (M-V-C)
- Controller handles user input
- Reusable components
- Common in web frameworks
Clean Architecture
Onion Layers in Cooking
Like an onion with core business rules at the center, protected by layers that depend inward.
Domain-centric architecture where dependencies point inward – core is independent of frameworks and UI.
- Domain at the center
- Dependencies point inward
- Framework independent
- Highly testable
Layered Architecture
The Fitness Tracker App
Like a fitness app where the UI layer, calculation layer, and data storage layer work independently.
Organizes a system into horizontal layers – each layer depends only on the layer below it.
- Presentation, Business, Data layers
- Clear separation of concerns
- Each layer has specific role
- Easy to understand and maintain
Null Object Pattern
Default Voicemail Greeting
Like a default voicemail greeting where instead of silence (null), callers hear a standard message.
Provides a default object instead of null – eliminates null checks and prevents null reference errors.
- Replaces null with object
- Default "do nothing" behavior
- Eliminates null checks
- Safer and cleaner code