Skip to content
StackPractices

Tag: design-pattern

Browse 128 practical software engineering resources tagged with "design-pattern". Discover code recipes, design patterns, documentation templates, and in-depth guides to help you build, deploy, and maintain production-ready solutions involving design-pattern.

Multi-Tenant Data Isolation Pattern

Isolate tenant data in shared infrastructure using row-level security, schema-per-tenant, or database-per-tenant strategies. A pattern for SaaS applications.

Pipes and Filters Pattern

Chain processing steps with independent filters connected by pipes. A pattern for data transformation pipelines where each step is reusable and composable.

Federated Identity Pattern

Delegate authentication to external identity providers. A pattern for integrating OAuth2, OIDC, SAML, and SSO across multiple services and organizations.

Voucher Pattern

Validate claims and delegate access using signed vouchers without exposing sensitive data. A security pattern for token-based authorization between services.

Abstract Factory for Cross-Platform UI Component Families

Create families of related objects without specifying concrete classes, enabling platform-specific implementations that share a common interface

Abstract Factory Pattern

Create families of related objects without specifying concrete classes. A creational design pattern for consistent object families.

Active Record Pattern

Wrap a database table or view in a class where an instance is tied to a single row, and the class provides methods for CRUD operations directly on the object.

Actor Model Pattern

Isolate state in actors that communicate only via messages. Each actor processes one message at a time, eliminating shared-state concurrency bugs by design.

Adapter Pattern

Convert the interface of a class into another interface clients expect. A structural design pattern for interface compatibility.

Adapter Pattern for Integrating External REST APIs

Use the Adapter pattern to normalize responses from external REST APIs into a consistent internal model without leaking third-party formats into your domain

Aggregate Pattern

Encapsulate a cluster of domain objects treated as a single unit for data changes. An Aggregate Root controls access to its internal entities and value objects.

Ambassador Pattern for Resilient Remote Service Access

Add a local ambassador that handles retries, circuit breaking, and monitoring when calling remote services, keeping the client simple and the service logic pure

Async Generator Pattern

Stream data lazily with async generators. Yield values one at a time as they become available, enabling memory-efficient processing of large or infinite data sequences.

Back-Pressure Pattern

Prevent upstream systems from overwhelming downstream consumers by propagating flow-control signals backward through the pipeline, ensuring stable throughput under load.

Backend for Frontend (BFF) Pattern

Create dedicated backend services tailored to the specific needs of each frontend client type, aggregating downstream APIs and optimizing data shapes per platform.

Blackboard Pattern

A shared knowledge space where independent specialized modules collaborate to solve complex problems by contributing partial solutions.

Blue-Green Deployment Pattern

Run two identical environments and switch traffic between them. Deploy to the idle environment, test it, then flip the router for instant release or rollback.

Bridge Pattern

Decouple an abstraction from its implementation so both can vary independently. A structural design pattern for platform independence.

Bridge Pattern for Decoupling UI Components from Themes

Separate an abstraction from its implementation so both can vary independently using the Bridge pattern for pluggable UI themes and rendering engines

Builder Pattern

Construct complex objects step by step. A creational design pattern for readable, configurable object construction.

Builder Pattern for Complex Configuration Objects

Use the Builder pattern to construct complex configuration objects with optional parameters and sensible defaults without telescoping constructors

Business Delegate Pattern

Reduce coupling between presentation and business tiers by introducing an intermediary that handles lookup, creation, and invocation of business services.

Cache-Aside Pattern

Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.

Canary Release Pattern

Route a small percentage of traffic to the new version while the rest stays on stable. Monitor health metrics and gradually increase or roll back based on results.

Chain of Responsibility for Request Processing Middleware

Pass requests along a chain of handlers where each handler decides whether to process the request or pass it to the next handler in the pipeline

Chain of Responsibility Pattern

Pass requests along a chain of handlers until one handles it. A behavioral design pattern for decoupling senders and receivers.

Claim Check Pattern

Store large payloads in external storage and pass only a lightweight reference token through the message bus, reducing broker load and preventing message size limits from being exceeded.

Command Pattern

Encapsulate a request as an object, letting you parameterize clients with queues, logs, and undoable operations. A behavioral design pattern.

Command Pattern with Undo/Redo in TypeScript

Implement the Command pattern to encapsulate requests as objects, enabling undo/redo operations, request queuing, and operation logging

Compensating Transaction Pattern

Undo the effects of a completed transaction by executing a counter-operation, enabling eventual consistency in long-running business processes across distributed services.

Composite Entity Pattern

Map a coarse-grained entity to multiple database tables by composing dependent objects, reducing the number of fine-grained remote calls in EJB and distributed systems.

Composite Pattern

Compose objects into tree structures to represent part-whole hierarchies. A structural design pattern for treating individual objects and compositions uniformly.

Composite Pattern for UI Component Trees in React

Use the Composite pattern to compose objects into tree structures, letting clients treat individual objects and compositions uniformly in UI component hierarchies

Content Delivery Network (CDN) Pattern

Distribute static and live content through geographically dispersed edge servers to reduce latency, improve availability, and offload origin infrastructure.

Context Object Pattern

Encapsulate state and services needed by multiple components into a single context object, reducing method signature bloat and decoupling code from specific environment details.

CQRS Pattern

Separate read and write operations into different models, optimizing each for their specific workload. A data pattern for scalable systems.

Data Access Object (DAO) Pattern

Abstract and encapsulate all access to a data source by exposing a clean interface while hiding persistence details from business logic.

Data Mapper Pattern

Separate in-memory domain objects from the database by delegating persistence to a dedicated mapper layer, keeping models framework-agnostic.

Database per Service Pattern

Give each microservice its own private database to ensure loose coupling, independent deployment, and technology heterogeneity across the application portfolio.

Dead Letter Channel Pattern

Route unprocessable messages to a separate dead letter queue for inspection and replay. Prevent poison messages from blocking the main queue indefinitely.

Decorator Pattern

Add new functionality to objects dynamically by wrapping them. A structural design pattern for flexible behavior extension.

Decorator Pattern for HTTP Request Pipelines

Use the Decorator pattern to compose cross-cutting concerns like logging, metrics, and retries into HTTP request pipelines without modifying core logic

Dependency Injection Container in TypeScript

Build a lightweight DI container that resolves class dependencies automatically, enabling testable, loosely-coupled applications without frameworks like Angular or InversifyJS

Deployment Ring Pattern

Roll out changes progressively in rings of increasing size. Start with a small group, verify health, then expand to larger rings before full deployment.

Distributed Lock Pattern

Coordinate mutually exclusive access to shared resources across distributed nodes using a consensus-based lock service, preventing race conditions in scaled-out systems.

Domain Event Pattern

Capture and publish major occurrences within a domain model to decouple side effects from core business logic and enable reactive workflows.

Eager Loading Pattern

Load related data in a single query rather than multiple round-trips, preventing the N+1 problem and improving read performance.

Entity-Component-System (ECS) Pattern

Compose entities from pure data components and process them with systems, enabling high-performance and flexible game object architecture without deep inheritance.

Event Bus Pattern

Decouple components by routing events through a central bus. A behavioral pattern for loosely coupled communication between modules.

Event-Carried State Transfer Pattern

Replicate state changes across services by publishing events that carry the full updated entity state, enabling consumers to maintain their own local copies without querying the source.

Event Sourcing Pattern

Store the state of an application as a sequence of events rather than storing only the current state. An architectural pattern for audit-friendly systems.

Facade Pattern

Provide a simplified interface to a complex subsystem. A structural pattern that hides implementation details behind a clean API.

Factory Pattern

Create objects without specifying the exact class to instantiate. A creational design pattern for flexible object creation.

Flyweight Pattern

Share objects to support large numbers of fine-grained objects efficiently. A structural design pattern for memory optimization.

Flyweight Pattern for Efficient Large-Scale Object Sharing

Use the Flyweight pattern to minimize memory usage by sharing as much data as possible between similar objects, essential for rendering large datasets

Front Controller Pattern

Route all incoming requests through a single handler that dispatches to the appropriate page command, centralizing request processing and security.

Gatekeeper Pattern

Place a validation and security boundary at the edge of a system to inspect, sanitize, and authenticate all incoming requests before they reach internal services.

Geode Pattern

Distribute data across nodes with partitioning so each node owns a shard. Horizontal scaling without shared state, with locality and fault isolation per partition.

Graceful Degradation Pattern

Degrade functionality instead of failing when dependencies are unavailable. Serve partial results, cached data, or fallback features to keep users running.

Idempotent Consumer Pattern

Process messages from a queue exactly once regardless of duplicates by using idempotent operations, unique identifiers, and deduplication strategies at the consumer level.

Identity Map Pattern

Ensure each object is loaded only once per transaction by caching instances by their primary key, preventing duplicate in-memory representations of the same database row.

Inbox Pattern

Use a dedicated inbox table or queue to record incoming events or requests, ensuring reliable delivery, deduplication, and idempotent processing even when downstream systems fail.

Intercepting Filter Pattern

Compose cross-cutting concerns into a chain of pluggable filters that intercept requests and responses, enabling reusable preprocessing and postprocessing logic.

Interpreter Pattern

Define a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences. A behavioral design pattern for mini-languages.

Interpreter Pattern for Domain-Specific Expression Languages

Build a language interpreter that evaluates expressions and rules by representing grammar as composable objects, useful for formulas, queries, and business rules

Iterator Pattern

Provide a way to access elements of a collection sequentially without exposing its underlying representation. A behavioral design pattern for traversal.

Iterator Pattern for Custom Collection Traversal in

Provide a way to access elements of an aggregate object sequentially without exposing its underlying representation using the Iterator pattern

Lock-Free Queue Pattern

Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.

Manager Pattern

Encapsulate lifecycle, coordination, and access control for a set of related objects through a dedicated manager class that centralizes operations and enforces invariants.

Marker Interface Pattern

Use empty interfaces as metadata tags to signal properties or capabilities at compile time and runtime, enabling type-safe checks without modifying class behavior.

Materialized View Pattern

Precompute and store expensive query results in a read-optimized cache to avoid repeated costly aggregation or joins across large datasets.

Mediator Pattern

Define an object that encapsulates how a set of objects interact. A behavioral design pattern for reducing chaotic dependencies.

Mediator Pattern for Loose Component Coupling in

Reduce chaotic dependencies between UI components by introducing a mediator that centralizes communication, preventing explicit references between peers

Memento Pattern

Capture and restore an object's internal state without violating encapsulation. A behavioral design pattern for undo/redo.

Memento Pattern for State Snapshot and Restoration

Capture and externalize an object's internal state without violating encapsulation, enabling undo, serialization, and state rollback in applications

Message Deduplication Pattern

Prevent duplicate processing by tracking message IDs with idempotency keys. Consumers check a store before processing to skip messages already handled.

Message Deferral Pattern

Delay message processing to a scheduled time. Move messages that cannot be processed now to a deferred queue or schedule them for later delivery.

Message Queue Load Leveling Pattern

Smooth traffic spikes by placing a queue between a producer and a consumer. The producer writes messages at any rate; the consumer processes them at a steady pace.

Mixin Pattern

Add reusable behavior to classes without inheritance by composing methods from shared objects into a target class.

Model-View-Presenter (MVP) Pattern

Separate presentation logic from the view by introducing a presenter that intermediates between the model and a passive view, enabling testable UI code.

Model-View-ViewModel (MVVM) Pattern

Bind UI components declaratively to a ViewModel that exposes data and commands, enabling automatic synchronization between view and state.

Module Pattern

Encapsulate private state and behavior inside a self-contained unit with a public API. A structural pattern for organizing code into reusable, scope-safe modules.

Multiton Pattern

Manage a map of named singleton instances, providing controlled access to a finite set of shared objects identified by keys.

MVC Pattern

Separate application into Model, View, and Controller components. An architectural design pattern for organized, maintainable code.

MVC Pattern in Modern Frontend Applications

Apply the Model-View-Controller pattern to React and Vue applications to separate data, UI, and interaction logic for maintainable component architecture

Null Object Pattern

Use a default object instead of null references to eliminate null checks and simplify client code. A behavioral pattern for safer defaults.

Object Pool Pattern

Reuse expensive objects instead of creating and destroying them repeatedly. A creational pattern for managing scarce resources efficiently.

Observer Pattern

Define a subscription mechanism to notify multiple objects about events. A behavioral design pattern for event-driven communication.

Outbox Pattern

Reliably publish domain events by persisting them in an outbox table within the same database transaction as the business operation.

Page Controller Pattern

Use a dedicated controller object for each logical page in a web application, handling the request and populating the view for that specific page.

Partial Class Pattern

Split a single class definition across multiple source files to separate auto-generated code from hand-written code, or to organize large classes by concern.

Plugin Pattern

Enable third-party extensions by defining extension points in a host system that loads and executes live external modules.

Priority Queue Pattern

Process tasks based on priority rather than arrival order, ensuring high-priority work gets resources before lower-priority tasks even if it arrived later.

Producer-Consumer Pattern

Decouple production and consumption with a shared queue. Producers generate items at their own pace; consumers process them independently through a bounded or unbounded buffer.

Prototype Pattern

Create new objects by copying existing ones. A creational design pattern for cloning and object duplication.

Prototype Pattern for Object Cloning and Configuration

Create new objects by copying existing ones, allowing pre-configured templates and avoiding subclass explosion when object creation is expensive

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it. A structural design pattern for access control, lazy loading, and logging.

Proxy Pattern for API Response Caching

How to implement a caching proxy that intercepts API calls and stores responses to reduce latency and avoid redundant network requests

Publish-Subscribe Pattern

Broadcast events to multiple independent subscribers. Publishers send messages to a topic without knowing which subscribers exist, enabling loose coupling between producers and consumers.

Queue-Based Load Leveling Pattern

Introduce a queue between task producers and consumers to smooth out traffic spikes, decouple components, and prevent downstream services from being overwhelmed by burst workloads.

Reactive Streams Pattern

Process asynchronous data streams with backpressure. Subscribers request N items at a time, preventing fast producers from overwhelming slow consumers.

Registry Pattern

Centralize access to shared services and objects via a lookup table. A structural pattern that decouples consumers from concrete implementations.

Repository Pattern

Abstract data access logic behind a clean interface. An architectural design pattern for testable, maintainable data layers.

Repository Pattern with TypeScript Generics

Implement a type-safe repository pattern in TypeScript that decouples data access logic from domain services using generics and interfaces

Retry Pattern

Retry an operation that has failed with transient errors, using configurable strategies like fixed delay, exponential backoff, or circuit breaker integration.

Role Pattern

Assign dynamic roles to objects at runtime instead of hard-coding behavior in class hierarchies, enabling flexible identity changes without inheritance bloat.

Saga Pattern

Manage distributed transactions across multiple services by chaining local transactions with compensating actions for rollbacks. A microservices pattern.

Scheduler Agent Supervisor Pattern

Coordinate resilient job scheduling by separating scheduling logic from execution agents and adding a supervisor that monitors, restarts, and manages agent lifecycle.

Sequential Convoy Pattern

Preserve message ordering for related messages in a distributed system by grouping them into ordered sequences and processing them one at a time through a single consumer.

Serverless DB Connection Pooling Pattern

Manage database connections across serverless invocations by using external connection poolers, connection reuse, and lightweight clients to avoid connection exhaustion.

Sharding Pattern

Split a large dataset into smaller partitions (shards) distributed across multiple servers to improve growth, performance, and availability beyond single-node limits.

Shed Load Pattern

Drop requests proactively under extreme load to protect the system. Reject excess traffic before it consumes resources and causes cascading failures.

Singleton Pattern

Ensure a class has only one instance and provide global access to it. A creational design pattern for controlled object creation.

SOLID Principles in TypeScript with Practical Examples

Apply the five SOLID principles to TypeScript code to improve maintainability, testability, and reduce coupling in object-oriented designs

Specification Pattern

Encapsulate business rules for selecting objects as reusable, composable predicate objects that can be combined with logical operators.

State Pattern

Allow an object to alter its behavior when its internal state changes. A behavioral design pattern for finite state machines.

Static Content Hosting Pattern

Deploy static files to a dedicated content delivery network or object storage to offload origin servers, reduce latency, and improve availability for assets like images, CSS, and JavaScript.

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. A behavioral design pattern for flexible behavior selection.

Template Method Pattern

Define the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure. A behavioral design pattern.

Thread Pool Pattern

Reuse a fixed set of threads for short-lived tasks instead of creating a new thread per task. Reduces overhead and bounds resource usage under load.

Throttling Pattern

Limit the rate at which a system processes requests or consumes resources to prevent overload, ensure fair usage, and maintain predictable performance under varying load.

Timeout Pattern

Prevent operations from hanging indefinitely by enforcing a maximum execution time. A resilience pattern for predictable response times.

Twin Pattern

Provide an alternative to multiple inheritance by linking two separate classes through mutual references, allowing them to delegate methods to each other as needed.

Type Object Pattern

Define game object types as runtime data rather than hard-coding them as classes, enabling designers to create new entity variants without recompiling the codebase.

Unit of Work Pattern

Track changes to in-memory objects during a business transaction and commit all updates atomically to the database, ensuring consistency.

Value Object Pattern

Model domain concepts by value rather than identity. An immutable object defined by its attributes, not by a unique ID.

Visitor Pattern

Represent an operation to be performed on elements of an object structure without changing the classes of the elements. A behavioral design pattern.

Visitor Pattern for Extensible Operations on Object

Separate algorithms from the objects they operate on, allowing new operations to be added without modifying existing element classes