Design Patterns
Design patterns are reusable solutions to common problems that arise when designing software. They are general solutions that can be applied to different situations and architectures. Design patterns provide a common vocabulary and way of thinking about software design principles, and they help to make software development more efficient by promoting code reusability and maintainability.
Design patterns are not strict rules or formulas; rather, they are guidelines that help developers to structure code in a particular way. Applying design patterns can streamline software development, making it more scalable, maintainable, and flexible.
History
Design patterns emerged as a formal engineering vocabulary in the 1990s so developers could name, compare, and reuse recurring structural solutions rather than rediscovering them on every project.
The Gang of Four (1994)
The movement gained momentum with the publication of Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides—commonly called the "Gang of Four" (GoF). Their catalog documented 23 patterns in object-oriented software, including Singleton, Factory Method, Adapter, and Observer.
Evolution Beyond Object-Oriented Code
Since 1994, design patterns have expanded across functional programming, reactive streams, web architectures, and distributed systems. While GoF grouped OOP patterns into creational, structural, and behavioral families, modern languages often express some of those ideas directly with first-class functions, modules, and reactive pipelines.
Common Patterns
Design patterns vary by programming paradigm because each paradigm offers different mechanisms for abstraction and composition. Studying these recurring templates helps you recognize structural problems quickly and communicate design intent clearly with teammates.
Pattern Families by Intent
Rather than memorizing dozens of pattern names in isolation, start by identifying where change or coupling occurs in your code: object creation, interface composition, or runtime collaboration.
Figure 1: Mapping recurring design problems to Creational, Structural, and Behavioral pattern families and their primary trade-offs.
Pattern Catalog Across Paradigms
The table below summarizes widely used patterns across object-oriented, functional, reactive, and procedural programming paradigms.
| Programming Paradigm |
Design Pattern |
Description |
| Object-Oriented Programming (OOP) |
Factory Method |
Creates objects without specifying the exact class to create. |
| Singleton |
Ensures a class has only one instance, and provides a global point of access to it. |
| Abstract Factory |
Creates families of related objects without specifying their concrete classes. |
| Builder |
Separates the construction of a complex object from its representation. |
| Prototype |
Creates a new object by copying an existing object. |
| Adapter |
Allows two incompatible interfaces to work together. |
| Bridge |
Decouples an abstraction from its implementation. |
| Facade |
Provides a simplified interface to a complex subsystem. |
| Functional Programming (FP) |
Higher-Order Functions |
Functions that can take functions as arguments and/or return functions as results. |
| Currying |
Technique of transforming a function with multiple arguments into a sequence of functions with a single argument. |
| Immutability |
Provides a number of benefits, such as increased safety, performance, and concurrency. |
| Reactive Programming |
Observer |
Objects that are notified when a subject's state changes. |
| Reactive Extensions (Rx) |
Library for composing asynchronous and event-based programs by using observable sequences. |
| Procedural Programming |
Module |
Encapsulates related functions and data into a reusable and maintainable unit of code. |
| Command |
Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. |
Core Object-Oriented Patterns in Practice
Prose definitions are only half the picture; seeing how a pattern separates responsibilities in code makes the trade-offs concrete. The three Python examples below demonstrate one pattern from each Gang of Four family—Creational, Structural, and Behavioral.
Creational: Factory Method
The Factory Method pattern centralizes object creation behind a single function or method so callers depend on a shared interface rather than concrete implementation classes. This keeps configuration parsing out of business logic and makes adding new backends straightforward.
from typing import Protocol
class Notifier(Protocol):
"""Shared contract so callers stay decoupled from transport details."""
def send(self, recipient: str, message: str) -> None: ...
class EmailNotifier:
def send(self, recipient: str, message: str) -> None:
print(f"[EMAIL] to={recipient}: {message}")
class WebhookNotifier:
def send(self, recipient: str, message: str) -> None:
print(f"[WEBHOOK] url={recipient}: {message}")
def create_notifier(channel: str) -> Notifier:
"""Factory Method: maps config string to a concrete Notifier."""
registry: dict[str, type[Notifier]] = {
"email": EmailNotifier,
"webhook": WebhookNotifier,
}
if channel not in registry:
# Fail fast on unknown configuration rather than returning None
raise ValueError(f"Unsupported notification channel: {channel!r}")
return registry[channel]()
# Caller relies only on the Notifier contract, not EmailNotifier directly
notifier = create_notifier("email")
notifier.send("team@sagecode.org", "Deployment succeeded")
Structural: Decorator
The Decorator pattern wraps an existing object with another object implementing the same interface, layering cross-cutting behavior such as logging, caching, or retries at runtime without modifying the original class or creating a deep inheritance hierarchy.
import time
from typing import Protocol
class DataFetcher(Protocol):
def fetch(self, key: str) -> str: ...
class DatabaseFetcher:
def fetch(self, key: str) -> str:
# Simulate slow primary storage lookup
return f"record:{key}"
class TimedCacheDecorator:
"""Structural Decorator: adds TTL caching around any DataFetcher."""
def __init__(self, inner: DataFetcher, ttl_seconds: float = 5.0) -> None:
self._inner = inner
self._ttl = ttl_seconds
self._cache: dict[str, tuple[str, float]] = {}
def fetch(self, key: str) -> str:
now = time.monotonic()
if key in self._cache:
value, expires_at = self._cache[key]
if now < expires_at:
return value # Cache hit within TTL window
# Cache miss or expired: delegate to wrapped fetcher
value = self._inner.fetch(key)
self._cache[key] = (value, now + self._ttl)
return value
# Compose behavior dynamically without altering DatabaseFetcher
fetcher: DataFetcher = TimedCacheDecorator(DatabaseFetcher(), ttl_seconds=10.0)
print(fetcher.fetch("user_42"))
Behavioral: Strategy
The Strategy pattern encapsulates interchangeable algorithms behind a uniform signature so behavior can be swapped at runtime without sprawling if/elif chains. In languages with first-class functions, a strategy can be either a class or a callable.
from typing import Callable
# Strategy type: any function computing a discounted total in cents
PricingStrategy = Callable[[int], int]
def no_discount(total_cents: int) -> int:
return total_cents
def percentage_discount(rate: float) -> PricingStrategy:
"""Returns a configured strategy while validating invariants upfront."""
if not 0.0 <= rate <= 1.0:
raise ValueError("Discount rate must be between 0.0 and 1.0")
return lambda total_cents: int(round(total_cents * (1.0 - rate)))
class CheckoutOrder:
def __init__(self, subtotal_cents: int, strategy: PricingStrategy) -> None:
self.subtotal_cents = subtotal_cents
self.strategy = strategy # Injected behavior, swappable at runtime
def final_total(self) -> int:
# Guard against negative totals from aggressive promotions
return max(0, self.strategy(self.subtotal_cents))
order = CheckoutOrder(10000, percentage_discount(0.15))
print(order.final_total()) # 8500
Web Development
Design patterns are widely used in web development to solve common problems that occur when building web applications. These patterns provide proven solutions to common design problems and help developers avoid reinventing the wheel.
For example, the Model-View-Controller (MVC) pattern is commonly used in web development as a way to separate an application into three distinct components - the Model (data and business logic), View (user interface) and Controller (intermediary between Model and View). This separation provides better organization, maintainability, and flexibility, as each component can be modified independently.
Other design patterns such as the Front Controller, Decorator, and Repository patterns are also commonly used in web development to solve specific problems related to handling HTTP requests, modifying the behavior of objects at runtime, and centralizing data access.
Model-View-Controller
The Model-View-Controller (MVC) pattern separates an application into three components:
- The Model represents the data and business logic
- The View represents the user interface
- The Controller acts as an intermediary between the Model and View
MVC allows for better organization and maintainability of code.
Single Page Application
The Single Page Application (SPA) pattern allows for faster and more responsive user experiences by loading content dynamically within a single web page. This avoids the traditional approach of loading a new page every time the user interacts with the application.
Front Controller
The Front Controller pattern consolidates all HTTP requests to a single point of control. This ensures that all requests go through a single component that can handle authentication, session management, and other common tasks.
Decorator
The Decorator pattern allows for dynamic modification of an object's behavior at runtime by wrapping it with additional code. In HTML, this could be used to modify the behavior of an element by adding attributes or classes.
Repository
The Repository pattern provides a centralized location for accessing data in an application. In HTML, this could be implemented as a JavaScript object or array that holds data for the entire application.
Using design patterns in web development can lead to more structured, modular, and maintainable code, helping developers build reliable applications consistently.
Parallel Computing
A design pattern for parallel computing is a repeatable solution to a common problem that arises when designing concurrent or distributed applications. These patterns help engineers structure workloads to exploit multiple cores or cluster nodes without introducing race conditions.
Common Parallel Patterns
The table below summarizes six foundational parallel execution models used in data processing and high-throughput backends.
| Design Pattern |
Description |
| MapReduce |
A programming model that divides input data into smaller chunks which are then processed independently and in parallel across a distributed network of processors or nodes. |
| Fork-Join |
A parallel programming technique that involves breaking a larger task into smaller sub-tasks that can be parallelized, executing them in parallel, and then joining the results back together. |
| Pipeline |
A design pattern that divides a larger task into stages, where each stage processes a subset of the data in parallel. The output of one stage becomes the input to the next stage until the final output is produced. |
| Master-Slave |
A design pattern that involves a master node controlling a group of worker nodes or slaves. The master assigns tasks to the worker nodes, which then execute them and send the results back to the master. |
| Data Parallelism |
A technique that involves dividing a data stream into smaller segments and distributing those segments across multiple processors. Each processor then performs an identical operation on its segment of the data, resulting in a parallel computation. |
| Bulk Synchronous Parallel (BSP) |
A parallel computing model that involves dividing a computational problem into smaller chunks or supersteps, which are then executed in parallel by a set of processors. Each superstep consists of computations on local data in each processor followed by global communication among processors to synchronize results. |
Concurrency Trade-Offs
Parallel patterns improve throughput only when the work per task outweighs coordination overhead. Splitting tasks too finely increases thread scheduling, serialization, and network synchronization costs, whereas coarse partitions risk stragglers leaving other workers idle.
Trade-Offs and Over-Engineering Pitfalls
Design patterns solve specific coupling and extensibility problems, but applying them indiscriminately adds layers of indirection that obscure control flow. Knowing when not to use a pattern is as important as knowing how to implement it.
The Singleton Global State Trap
The Singleton pattern restricts a class to one global instance, which often looks convenient for configuration or database pools. In practice, a Singleton behaves like hidden global mutable state: functions that call Config.getInstance() hide their dependencies from callers, making parallel unit tests leak state across test cases and turning future multi-tenant support into a major refactor. Passing a single shared instance explicitly via dependency injection achieves the same resource sharing without global coupling.
Premature Abstraction and Unnecessary Indirection
Introducing an Abstract Factory, Strategy interface, and Adapter chain when only one concrete implementation exists—and no second variant is planned—doubles the number of files readers must navigate without delivering flexibility. Start with direct functions or classes, and extract a pattern only when a second concrete requirement reveals the true axis of variation.