Cloud & ArchitectureComplete guide

Design Patterns

Design patterns describe proven arrangements of responsibilities and collaborations for recurring software design problems.

Overview

Design patterns are named arrangements of responsibilities that help teams discuss recurring construction, composition, collaboration, and state-change problems. They are neither frameworks nor goals: each moves complexity and is justified only by a concrete force such as interchangeable policy, incompatible integration, layered behavior, controlled creation, notification fan-out, or lifecycle transitions. Modern C# records, delegates, pattern matching, generics, dependency injection, middleware, and first-class functions often express the same intent with less ceremony than classic class diagrams. A good implementation keeps selection and composition visible, preserves substitution, owns failure and concurrency semantics, and is tested through behavior rather than participant names. Patterns can combine—such as a factory composing strategies and decorators around an adapter—but excessive abstraction, speculative extension points, service location, and generic repositories can make simple changes harder. Refactor toward a pattern after the pressure becomes clear and remove it when it no longer earns its cost.

What you will learn

  • Classify creational, structural, and behavioral patterns by the pressure they address.
  • Implement Strategy, Adapter, Decorator, and Factory using modern C# composition.
  • Distinguish similar patterns by intent rather than diagram shape.
  • Select language or framework features when they express the intent more simply.
  • Test substitutability, ordering, translation, failure, and composition.
  • Recognize and remove speculative or misleading pattern use.

Prerequisites

  • C# interfaces, records, delegates, generics, dependency injection, and testing.
  • SOLID principles, composition, coupling, cohesion, and application boundaries.
  • Ability to describe a real change pressure before choosing a structure.

When to use Design Patterns

Good fit

  • Two or more policies must vary behind one stable contract.
  • An external contract must be translated at a boundary.
  • Ordered cross-cutting behavior must wrap a capability.
  • Construction or lifecycle rules are complex enough to centralize.

Choose another approach when

  • A direct method, switch, delegate, or framework feature is clearer.
  • Variation is speculative and has only one stable implementation.
  • The abstraction hides ownership or turns dependencies into runtime lookup.

Key concepts

Creational patterns

Factories, builders, and prototypes separate construction decisions from consumers.

Structural patterns

Adapters, decorators, composites, and facades shape how objects and systems fit together.

Behavioral patterns

Strategies, observers, commands, and mediators organize algorithms and collaboration.

Pattern trade-offs

Each pattern shifts complexity; the benefit must outweigh indirection, objects, and conventions.

Strategy and policy

Strategy encapsulates interchangeable algorithms while keeping selection rules visible at composition.

Adapter and boundary translation

Adapter converts an external or legacy contract into an application-owned interface and contains semantic mismatch.

Decorator and pipelines

Decorator adds ordered behavior around a stable contract without changing the wrapped implementation.

Factory and composition

Factories centralize nontrivial construction and selection without becoming global service locators.

Architecture

A caller depends on a stable strategy contract while the composition root selects a behavior suited to current policy.

Caller
Strategy contract
Concrete strategy
External capability

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The pricing sample combines Strategy for discounts, Adapter for a legacy tax gateway, Decorator for a safety limit, and Factory for explicit composition, with one focused test per pressure.

  1. 01
    Name the force

    Describe what varies, what must remain stable, and which dependency or responsibility causes pain.

  2. 02
    Choose the smallest intent

    Compare direct code, a language feature, framework middleware, and the candidate pattern.

  3. 03
    Define the contract

    Express only behavior consumers need and preserve substitutability.

  4. 04
    Implement participants

    Keep each strategy, adapter, decorator, or creator cohesive and side effects explicit.

  5. 05
    Compose visibly

    Select implementations in a composition root or focused factory, not hidden service location.

  6. 06
    Test semantics

    Verify alternatives, translation, ordering, errors, concurrency, and boundary cases.

  7. 07
    Reassess cost

    Measure comprehension and change impact and simplify when the pattern no longer earns its indirection.

Code example

Strategy replaces branching that changes for different pricing policies with a focused, selectable behavior.

PricingStrategy.cs
public interface IPricingStrategy
{
    decimal Calculate(Order order);
}

public sealed class LoyaltyPricing : IPricingStrategy
{
    public decimal Calculate(Order order) =>
        order.Subtotal >= 100m
            ? order.Subtotal * 0.90m
            : order.Subtotal;
}

public sealed class Checkout(IPricingStrategy pricing)
{
    public decimal Total(Order order) => pricing.Calculate(order);
}

Testing strategy

Test the behavioral promise and trade-off of a pattern, not merely class existence.

  • Run the same contract tests against every strategy implementation.
  • Test adapter units, rounding, missing fields, timeouts, and error translation.
  • Verify decorator ordering, short-circuiting, and exception behavior.
  • Test factory selection and unsupported configuration.
  • Exercise observer duplication, ordering, and failure isolation where used.
  • Add concurrency tests for shared or stateful participants.

Security considerations

Patterns can centralize security policy or hide it, so trust boundaries and ordering must remain explicit.

  • Do not use a decorator as the only resource-authorization check when callers can bypass it.
  • Validate and normalize data inside adapters at external boundaries.
  • Keep factories from becoming unrestricted service locators.
  • Redact sensitive inputs in logging decorators.
  • Fail closed when a security policy participant is missing or fails.

Performance and scalability

Virtual dispatch is usually small; allocation, reflection, network work, and long decorator chains matter more and must be measured.

  • Profile the real composed path before optimizing dispatch.
  • Keep hot strategies allocation-conscious.
  • Avoid repeated serialization or mapping between decorators.
  • Cache immutable factory products only with correct lifetimes.
  • Measure chain depth, latency contribution, and failure amplification.

Deployment and operations

Selection rules and external adapters are configuration-sensitive production behavior.

  • Validate factory configuration at startup.
  • Version application-owned adapter contracts.
  • Roll out new strategies behind explicit flags when outcomes change.
  • Trace concrete participant names and timing without leaking data.
  • Smoke-test the production composition, not isolated defaults.

Common problems and fixes

Many one-line classes obscure behavior.

Likely cause: A pattern was applied without real variation.

Fix: Inline participants or use delegates and direct composition.

A new strategy requires changing callers.

Likely cause: Selection leaked outside composition.

Fix: Centralize selection in one factory or root.

Decorator order changes results.

Likely cause: Pipeline semantics are undocumented.

Fix: Define and test explicit ordering.

Adapter leaks vendor types.

Likely cause: Translation stops at the boundary.

Fix: Map inputs, outputs, errors, and units into owned contracts.

Factory resolves arbitrary services.

Likely cause: It became a service locator.

Fix: Inject explicit dependencies and return a focused product.

Pattern names create false confidence.

Likely cause: Failure, concurrency, and lifecycle semantics are missing.

Fix: Document and test operational behavior.

Best practices

  • Name the design pressure before naming a pattern.
  • Prefer language features and simple composition when they solve the problem clearly.
  • Keep pattern participants cohesive and make selection rules visible.
  • Document trade-offs when a pattern introduces meaningful indirection.
  • Test all implementations against the same behavioral contract.
  • Keep boundary translation complete inside adapters.
  • Make decorator order and short-circuit behavior explicit.
  • Refactor away patterns that no longer reduce change cost.

Production checklist

  • A concrete force and expected benefit justify every pattern.
  • Contracts are minimal and substitutable.
  • Selection and composition are visible.
  • Adapters own complete semantic translation.
  • Decorator order and bypass rules are tested.
  • Factories do not hide arbitrary dependency lookup.
  • Failure, security, concurrency, and lifetime behavior are explicit.
  • The design is simpler than the branching or coupling it replaces.

Common interview questions

How do Strategy and State differ?

They have similar structure, but Strategy selects an interchangeable algorithm while State models behavior that changes with an object's internal state transitions.

What is the difference between Adapter and Facade?

Adapter changes an interface so a client can use it. Facade provides a simpler entry point over a subsystem without necessarily adapting an incompatible contract.

When is a pattern over-engineering?

When the predicted variation is unlikely, the simpler design is already easy to change, or the added abstractions make ownership and behavior harder to understand.

Decorator or middleware?

Both form ordered pipelines; decorators wrap an application contract, while middleware usually surrounds a framework request pipeline.

Factory or dependency injection container?

A factory owns focused runtime construction or selection. A container composes the object graph and should not be resolved from business code.

When is a delegate better than Strategy?

When behavior has little state or lifecycle and a named function clearly expresses the variation with less ceremony.

How should an Adapter handle failures?

Translate vendor errors, units, nullability, retries, and cancellation into the application-owned contract rather than leaking them.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Design Patterns Pricing

A .NET 10 pricing workflow applying Strategy, Adapter, Decorator, and Factory to real behavior variation, legacy integration, cross-cutting policy, and composition pressures.

.NET 10Design PatternsSOLIDxUnit
dedicated-samplestrategyadapterdecoratorfactory
Run
dotnet run --project src/DesignPatternsPricing
Test
dotnet test DesignPatternsPricing.slnx