Skip to content

15 Must-Know Design Patterns Every Software Engineer and Architect Should Understand

Design patterns are reusable solutions to common software design problems. They are not copy-paste code templates, but proven architectural ideas that help teams build systems that are easier to extend, test, maintain, a...

Ekanatha Reddy Urivakili27 min1,910 words

Design patterns are reusable solutions to common software design problems. They are not copy-paste code templates, but proven architectural ideas that help teams build systems that are easier to extend, test, maintain, and scale.

As a Senior Architect or Principal Software Engineer, design patterns are not just theory. They help you make better decisions around extensibility, dependency management, system boundaries, business rules, and long-term maintainability.


Pattern Categories

These 15 patterns can be grouped into three major categories:

CategoryPurposePatterns
Creational PatternsHow objects are createdSingleton, Factory Method, Builder
Structural PatternsHow objects/classes are composedAdapter, Decorator, Facade, Proxy, Composite
Behavioural PatternsHow objects communicate and behaveObserver, Strategy, Command, Iterator, State, Template Method, Chain of Responsibility

1. Singleton Pattern

What it means

The Singleton pattern ensures that only one instance of a class exists in the application and provides a global access point to it.

Real-world example

A logging service, configuration provider, cache manager, or application settings object may need to exist only once.

C# Example

public sealed class AppConfiguration
{
    private static readonly Lazy<AppConfiguration> _instance =
        new Lazy<AppConfiguration>(() => new AppConfiguration());

    public static AppConfiguration Instance => _instance.Value;

    public string EnvironmentName { get; private set; }

    private AppConfiguration()
    {
        EnvironmentName = "Production";
    }
}

Usage:

var config = AppConfiguration.Instance;
Console.WriteLine(config.EnvironmentName);

When to use

Use Singleton when:

You genuinely need one shared instance across the application.

Examples:

Configuration service
Logging service
In-memory cache
Feature flag provider

Architect’s warning

Singleton is often overused. In modern .NET applications, Dependency Injection is usually preferred.

Instead of manually implementing Singleton, you can register the dependency like this:

builder.Services.AddSingleton<IAppConfiguration, AppConfiguration>();

Blogging explanation

A Singleton looks simple, but it can introduce hidden dependencies and make testing harder. In enterprise systems, prefer DI-managed singletons rather than static singleton classes.


2. Factory Method Pattern

What it means

Factory Method creates objects without exposing the exact creation logic to the caller.

Real-world example

A payment system may support multiple payment providers:

Stripe
PayPal
Checkout.com
Adyen
Worldpay

The application should not create each provider directly everywhere.

C# Example

public interface IPaymentProcessor
{
    Task ProcessPaymentAsync(decimal amount);
}

public class StripePaymentProcessor : IPaymentProcessor
{
    public Task ProcessPaymentAsync(decimal amount)
    {
        Console.WriteLine($"Processing {amount} using Stripe");
        return Task.CompletedTask;
    }
}

public class CheckoutPaymentProcessor : IPaymentProcessor
{
    public Task ProcessPaymentAsync(decimal amount)
    {
        Console.WriteLine($"Processing {amount} using Checkout.com");
        return Task.CompletedTask;
    }
}

Factory:

public class PaymentProcessorFactory
{
    public IPaymentProcessor Create(string provider)
    {
        return provider.ToLower() switch
        {
            "stripe" => new StripePaymentProcessor(),
            "checkout" => new CheckoutPaymentProcessor(),
            _ => throw new NotSupportedException($"Provider {provider} is not supported")
        };
    }
}

Usage:

var factory = new PaymentProcessorFactory();
var processor = factory.Create("checkout");

await processor.ProcessPaymentAsync(100);

When to use

Use Factory Method when:

Object creation is complex
Object type depends on runtime input
You want to avoid tight coupling
You support multiple implementations of the same abstraction

Blogging explanation

Factory Method is common in payment platforms, notification systems, reporting engines, and integration-heavy applications. It keeps the calling code clean and allows new implementations to be added with minimal impact.


3. Builder Pattern

What it means

Builder constructs complex objects step by step.

Real-world example

Creating an order, invoice, report, email message, or API request with many optional fields.

C# Example

public class Invoice
{
    public string CustomerName { get; set; }
    public string BillingAddress { get; set; }
    public List<string> Items { get; set; } = new();
    public decimal Tax { get; set; }
    public decimal Discount { get; set; }
}

Builder:

public class InvoiceBuilder
{
    private readonly Invoice _invoice = new();

    public InvoiceBuilder ForCustomer(string customerName)
    {
        _invoice.CustomerName = customerName;
        return this;
    }

    public InvoiceBuilder WithBillingAddress(string address)
    {
        _invoice.BillingAddress = address;
        return this;
    }

    public InvoiceBuilder AddItem(string item)
    {
        _invoice.Items.Add(item);
        return this;
    }

    public InvoiceBuilder WithTax(decimal tax)
    {
        _invoice.Tax = tax;
        return this;
    }

    public InvoiceBuilder WithDiscount(decimal discount)
    {
        _invoice.Discount = discount;
        return this;
    }

    public Invoice Build()
    {
        return _invoice;
    }
}

Usage:

var invoice = new InvoiceBuilder()
    .ForCustomer("Acme Ltd")
    .WithBillingAddress("London, UK")
    .AddItem("Software License")
    .AddItem("Support Package")
    .WithTax(20)
    .WithDiscount(10)
    .Build();

When to use

Use Builder when object construction has many optional parts.

Blogging explanation

Builder improves readability and avoids constructors with too many parameters. It is especially useful when constructing DTOs, reports, test data, domain objects, and configuration objects.


4. Adapter Pattern

What it means

Adapter allows incompatible interfaces to work together.

Real-world example

Your application expects one interface, but a third-party service provides a different one.

Example:

Your system expects:

public interface IPaymentGateway
{
    Task PayAsync(decimal amount);
}

But a legacy provider has this:

public class LegacyPaymentService
{
    public void MakePayment(double value)
    {
        Console.WriteLine($"Paid {value} using legacy provider");
    }
}

Adapter:

public class LegacyPaymentAdapter : IPaymentGateway
{
    private readonly LegacyPaymentService _legacyPaymentService;

    public LegacyPaymentAdapter(LegacyPaymentService legacyPaymentService)
    {
        _legacyPaymentService = legacyPaymentService;
    }

    public Task PayAsync(decimal amount)
    {
        _legacyPaymentService.MakePayment((double)amount);
        return Task.CompletedTask;
    }
}

Usage:

IPaymentGateway gateway =
    new LegacyPaymentAdapter(new LegacyPaymentService());

await gateway.PayAsync(250);

When to use

Use Adapter when:

You integrate with legacy systems
Third-party APIs do not match your domain interface
You want to isolate external service changes

Blogging explanation

Adapter is one of the most practical enterprise patterns. It helps protect your application from vendor-specific APIs and keeps your domain model clean.


5. Decorator Pattern

What it means

Decorator adds new behavior to an object dynamically without changing the original class.

Real-world example

Adding logging, caching, validation, metrics, retry, or authorization around a service.

C# Example

Base interface:

public interface IOrderService
{
    Task PlaceOrderAsync(int orderId);
}

Core service:

public class OrderService : IOrderService
{
    public Task PlaceOrderAsync(int orderId)
    {
        Console.WriteLine($"Order {orderId} placed.");
        return Task.CompletedTask;
    }
}

Logging decorator:

public class LoggingOrderServiceDecorator : IOrderService
{
    private readonly IOrderService _inner;

    public LoggingOrderServiceDecorator(IOrderService inner)
    {
        _inner = inner;
    }

    public async Task PlaceOrderAsync(int orderId)
    {
        Console.WriteLine($"Starting order placement for {orderId}");
        await _inner.PlaceOrderAsync(orderId);
        Console.WriteLine($"Finished order placement for {orderId}");
    }
}

Usage:

IOrderService service =
    new LoggingOrderServiceDecorator(new OrderService());

await service.PlaceOrderAsync(101);

When to use

Use Decorator when you want to add behavior without modifying existing code.

Blogging explanation

Decorator supports the Open/Closed Principle. It is commonly used in enterprise applications for cross-cutting concerns like logging, caching, tracing, validation, and retry handling.


6. Facade Pattern

What it means

Facade provides a simple interface over a complex subsystem.

Real-world example

An order checkout flow may involve:

Inventory service
Payment service
Discount service
Shipping service
Notification service

Instead of exposing all services to the controller, create a facade.

C# Example

public class CheckoutFacade
{
    private readonly InventoryService _inventory;
    private readonly PaymentService _payment;
    private readonly ShippingService _shipping;
    private readonly NotificationService _notification;

    public CheckoutFacade(
        InventoryService inventory,
        PaymentService payment,
        ShippingService shipping,
        NotificationService notification)
    {
        _inventory = inventory;
        _payment = payment;
        _shipping = shipping;
        _notification = notification;
    }

    public async Task CompleteCheckoutAsync(int orderId)
    {
        await _inventory.ReserveStockAsync(orderId);
        await _payment.TakePaymentAsync(orderId);
        await _shipping.CreateShipmentAsync(orderId);
        await _notification.SendConfirmationAsync(orderId);
    }
}

When to use

Use Facade when a client should not know the complexity of multiple subsystems.

Blogging explanation

Facade is valuable in application services, orchestration layers, and API endpoints. It simplifies client code and keeps complexity hidden behind a clean interface.


7. Proxy Pattern

What it means

Proxy controls access to another object.

Real-world example

A proxy can add:

Lazy loading
Security checks
Caching
Remote service access
Rate limiting

C# Example: Caching Proxy

public interface IProductService
{
    Task<string> GetProductNameAsync(int productId);
}

Real service:

public class ProductService : IProductService
{
    public Task<string> GetProductNameAsync(int productId)
    {
        Console.WriteLine("Fetching product from database...");
        return Task.FromResult($"Product-{productId}");
    }
}

Proxy:

public class CachedProductServiceProxy : IProductService
{
    private readonly IProductService _inner;
    private readonly Dictionary<int, string> _cache = new();

    public CachedProductServiceProxy(IProductService inner)
    {
        _inner = inner;
    }

    public async Task<string> GetProductNameAsync(int productId)
    {
        if (_cache.ContainsKey(productId))
        {
            return _cache[productId];
        }

        var productName = await _inner.GetProductNameAsync(productId);
        _cache[productId] = productName;

        return productName;
    }
}

Blogging explanation

Proxy is useful when direct access to an object needs to be controlled. In distributed systems, API gateways, service clients, and security wrappers often behave like proxies.


8. Composite Pattern

What it means

Composite treats individual objects and groups of objects uniformly.

Real-world example

A file system:

File
Folder
Folder contains files and other folders

Both files and folders can be treated as file system items.

C# Example

public interface IFileSystemItem
{
    void Display(int depth);
}

File:

public class FileItem : IFileSystemItem
{
    private readonly string _name;

    public FileItem(string name)
    {
        _name = name;
    }

    public void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + _name);
    }
}

Folder:

public class FolderItem : IFileSystemItem
{
    private readonly string _name;
    private readonly List<IFileSystemItem> _items = new();

    public FolderItem(string name)
    {
        _name = name;
    }

    public void Add(IFileSystemItem item)
    {
        _items.Add(item);
    }

    public void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + _name);

        foreach (var item in _items)
        {
            item.Display(depth + 2);
        }
    }
}

Usage:

var root = new FolderItem("Root");
root.Add(new FileItem("readme.md"));

var src = new FolderItem("src");
src.Add(new FileItem("Program.cs"));

root.Add(src);
root.Display(1);

Blogging explanation

Composite is useful for tree structures such as menus, categories, permissions, organization charts, UI components, and file systems.


9. Observer Pattern

What it means

Observer notifies multiple objects when state changes.

Real-world example

When an order is placed, multiple systems may need to react:

Send email
Update inventory
Publish event
Generate invoice
Notify warehouse

C# Example

public interface IOrderObserver
{
    Task OnOrderPlacedAsync(int orderId);
}

Observers:

public class EmailNotificationObserver : IOrderObserver
{
    public Task OnOrderPlacedAsync(int orderId)
    {
        Console.WriteLine($"Email sent for order {orderId}");
        return Task.CompletedTask;
    }
}

public class InventoryObserver : IOrderObserver
{
    public Task OnOrderPlacedAsync(int orderId)
    {
        Console.WriteLine($"Inventory updated for order {orderId}");
        return Task.CompletedTask;
    }
}

Subject:

public class OrderPublisher
{
    private readonly List<IOrderObserver> _observers = new();

    public void Subscribe(IOrderObserver observer)
    {
        _observers.Add(observer);
    }

    public async Task PlaceOrderAsync(int orderId)
    {
        Console.WriteLine($"Order {orderId} placed");

        foreach (var observer in _observers)
        {
            await observer.OnOrderPlacedAsync(orderId);
        }
    }
}

Blogging explanation

Observer is the foundation of event-driven systems. In modern architecture, this pattern appears as domain events, message queues, pub/sub systems, webhooks, and event notifications.


10. Strategy Pattern

What it means

Strategy allows you to swap algorithms at runtime.

Real-world example

Different discount strategies:

No discount
Seasonal discount
Premium customer discount
Black Friday discount

C# Example

public interface IDiscountStrategy
{
    decimal ApplyDiscount(decimal amount);
}

Strategies:

public class NoDiscountStrategy : IDiscountStrategy
{
    public decimal ApplyDiscount(decimal amount) => amount;
}

public class PremiumCustomerDiscountStrategy : IDiscountStrategy
{
    public decimal ApplyDiscount(decimal amount) => amount * 0.90m;
}

public class BlackFridayDiscountStrategy : IDiscountStrategy
{
    public decimal ApplyDiscount(decimal amount) => amount * 0.70m;
}

Context:

public class PricingService
{
    private readonly IDiscountStrategy _discountStrategy;

    public PricingService(IDiscountStrategy discountStrategy)
    {
        _discountStrategy = discountStrategy;
    }

    public decimal CalculateFinalPrice(decimal amount)
    {
        return _discountStrategy.ApplyDiscount(amount);
    }
}

Usage:

var service = new PricingService(new BlackFridayDiscountStrategy());
var finalPrice = service.CalculateFinalPrice(100);

Console.WriteLine(finalPrice);

Blogging explanation

Strategy removes large if-else or switch blocks. It is excellent for pricing, tax calculation, routing rules, validation rules, payment selection, sorting, and recommendation logic.


11. Command Pattern

What it means

Command encapsulates a request as an object.

Real-world example

A banking application may perform commands like:

Create account
Transfer money
Cancel payment
Refund payment
Generate statement

Each action can be represented as a command.

C# Example

public interface ICommand
{
    Task ExecuteAsync();
}

Command:

public class SendEmailCommand : ICommand
{
    private readonly string _email;

    public SendEmailCommand(string email)
    {
        _email = email;
    }

    public Task ExecuteAsync()
    {
        Console.WriteLine($"Sending email to {_email}");
        return Task.CompletedTask;
    }
}

Invoker:

public class CommandInvoker
{
    public async Task ExecuteAsync(ICommand command)
    {
        await command.ExecuteAsync();
    }
}

Usage:

var command = new SendEmailCommand("customer@example.com");
var invoker = new CommandInvoker();

await invoker.ExecuteAsync(command);

Blogging explanation

Command is commonly used in CQRS, task queues, background jobs, undo/redo functionality, and workflow systems.

In CQRS, you may see commands like:

CreateOrderCommand
CancelOrderCommand
UpdateCustomerAddressCommand

12. Iterator Pattern

What it means

Iterator allows traversal through a collection without exposing its internal structure.

Real-world example

Looping through a custom collection such as paginated database results, search results, tree nodes, or API records.

C# Example

C# already supports Iterator using IEnumerable.

public class OrderCollection
{
    private readonly List<string> _orders = new()
    {
        "Order-1",
        "Order-2",
        "Order-3"
    };

    public IEnumerable<string> GetOrders()
    {
        foreach (var order in _orders)
        {
            yield return order;
        }
    }
}

Usage:

var orders = new OrderCollection();

foreach (var order in orders.GetOrders())
{
    Console.WriteLine(order);
}

Blogging explanation

Iterator hides the internal representation of a collection. In .NET, IEnumerable, IEnumerator, and yield return are practical implementations of this pattern.


13. State Pattern

What it means

State changes an object’s behavior based on its internal state.

Real-world example

An order can move through several states:

Created
Paid
Packed
Shipped
Delivered
Cancelled

The allowed actions depend on the current state.

C# Example

public interface IOrderState
{
    void Next(OrderContext context);
}

States:

public class CreatedState : IOrderState
{
    public void Next(OrderContext context)
    {
        Console.WriteLine("Order paid.");
        context.SetState(new PaidState());
    }
}

public class PaidState : IOrderState
{
    public void Next(OrderContext context)
    {
        Console.WriteLine("Order shipped.");
        context.SetState(new ShippedState());
    }
}

public class ShippedState : IOrderState
{
    public void Next(OrderContext context)
    {
        Console.WriteLine("Order delivered.");
    }
}

Context:

public class OrderContext
{
    private IOrderState _state;

    public OrderContext()
    {
        _state = new CreatedState();
    }

    public void SetState(IOrderState state)
    {
        _state = state;
    }

    public void MoveNext()
    {
        _state.Next(this);
    }
}

Usage:

var order = new OrderContext();

order.MoveNext();
order.MoveNext();
order.MoveNext();

Blogging explanation

State pattern is useful when business workflows have strict transitions. It avoids messy conditional logic and makes state-specific behavior explicit.


14. Template Method Pattern

What it means

Template Method defines the skeleton of an algorithm and allows subclasses to override specific steps.

Real-world example

Generating reports:

Load data
Validate data
Format data
Export report
Send notification

The overall process is the same, but some steps differ depending on the report type.

C# Example

public abstract class ReportGenerator
{
    public void GenerateReport()
    {
        LoadData();
        FormatData();
        Export();
    }

    protected abstract void LoadData();
    protected abstract void FormatData();

    protected virtual void Export()
    {
        Console.WriteLine("Exporting report as PDF");
    }
}

Concrete implementation:

public class SalesReportGenerator : ReportGenerator
{
    protected override void LoadData()
    {
        Console.WriteLine("Loading sales data");
    }

    protected override void FormatData()
    {
        Console.WriteLine("Formatting sales report");
    }
}

Usage:

ReportGenerator report = new SalesReportGenerator();
report.GenerateReport();

Blogging explanation

Template Method works well for workflows where the high-level process is fixed but individual steps vary. It is useful in import/export pipelines, report generation, payment processing flows, and document generation.


15. Chain of Responsibility Pattern

What it means

Chain of Responsibility passes a request through a chain of handlers until one handles it.

Real-world example

In ASP.NET Core middleware pipeline:

Authentication
Authorization
Logging
Exception handling
Routing
Endpoint execution

Each middleware decides whether to process the request or pass it to the next component.

C# Example

public abstract class SupportHandler
{
    protected SupportHandler? NextHandler;

    public void SetNext(SupportHandler nextHandler)
    {
        NextHandler = nextHandler;
    }

    public abstract void Handle(string issue);
}

Handlers:

public class LevelOneSupport : SupportHandler
{
    public override void Handle(string issue)
    {
        if (issue == "password-reset")
        {
            Console.WriteLine("Level 1 handled password reset.");
        }
        else
        {
            NextHandler?.Handle(issue);
        }
    }
}

public class LevelTwoSupport : SupportHandler
{
    public override void Handle(string issue)
    {
        if (issue == "payment-failure")
        {
            Console.WriteLine("Level 2 handled payment failure.");
        }
        else
        {
            NextHandler?.Handle(issue);
        }
    }
}

public class EngineeringSupport : SupportHandler
{
    public override void Handle(string issue)
    {
        Console.WriteLine("Engineering team handled complex issue.");
    }
}

Usage:

var levelOne = new LevelOneSupport();
var levelTwo = new LevelTwoSupport();
var engineering = new EngineeringSupport();

levelOne.SetNext(levelTwo);
levelTwo.SetNext(engineering);

levelOne.Handle("payment-failure");

Blogging explanation

Chain of Responsibility is heavily used in middleware, request pipelines, validation chains, approval workflows, logging pipelines, and support escalation systems.


How These Patterns Map to Modern .NET Architecture

Design PatternCommon .NET Usage
SingletonDI singleton services, configuration, caching
Factory MethodCreating service implementations dynamically
BuilderFluent APIs, test data builders, complex DTO creation
AdapterWrapping third-party APIs or legacy systems
DecoratorLogging, caching, validation, retry wrappers
FacadeApplication services, orchestration services
ProxyCaching proxy, API gateway, lazy loading
CompositeMenus, permissions, file systems, tree structures
ObserverDomain events, pub/sub, message queues
StrategyPricing rules, tax rules, payment routing
CommandCQRS, background jobs, task execution
IteratorIEnumerable, pagination, streaming data
StateWorkflow engines, order lifecycle, ticket lifecycle
Template MethodReport generation, import/export processing
Chain of ResponsibilityASP.NET Core middleware, validation pipelines

Suggested Blog Structure

You can write the blog like this:

1. Introduction
2. Why Design Patterns Matter
3. Creational Patterns
   - Singleton
   - Factory Method
   - Builder
4. Structural Patterns
   - Adapter
   - Decorator
   - Facade
   - Proxy
   - Composite
5. Behavioural Patterns
   - Observer
   - Strategy
   - Command
   - Iterator
   - State
   - Template Method
   - Chain of Responsibility
6. Real-world .NET Use Cases
7. Common Mistakes
8. Final Thoughts

Common Mistakes Engineers Make with Design Patterns

1. Using patterns too early

Do not use a pattern just because it looks professional. Use it when the problem actually needs it.

2. Overengineering simple code

Sometimes a simple method is better than creating five interfaces and ten classes.

3. Confusing Strategy with Factory

Factory creates objects.

Strategy changes behavior.

4. Confusing Decorator with Proxy

Decorator adds behavior.

Proxy controls access.

5. Misusing Singleton

Singleton can make testing harder if used as a static global object. Prefer Dependency Injection.


Senior Architect View

Design patterns are not about memorising definitions. They are about recognising design forces:

What changes frequently?
What should remain stable?
Where is coupling increasing?
Where is object creation becoming complex?
Where are business rules becoming conditional-heavy?
Where do we need extensibility without changing existing code?

A good architect does not force design patterns into the system. A good architect recognises when a pattern naturally solves a recurring design problem.


Principal Engineer Interview-Style Explanation

You can explain design patterns like this:

Design patterns are reusable approaches to common software design problems. I use them to improve maintainability, extensibility, and testability. For example, I would use Strategy when business rules vary at runtime, Factory when object creation depends on runtime conditions, Adapter when integrating with third-party systems, and Chain of Responsibility for request pipelines such as middleware or validation. However, I avoid applying patterns blindly because unnecessary abstraction can make the system harder to understand.


Best Patterns to Focus on for Tech Lead / Architect Interviews

For backend and enterprise architecture roles, these are especially important:

Factory Method
Strategy
Decorator
Adapter
Facade
Observer
Command
Chain of Responsibility
State
Builder

These appear frequently in:

.NET applications
AWS-based systems
Microservices
Payment platforms
Event-driven architecture
Clean Architecture
CQRS
DDD
Middleware pipelines
Third-party integrations

Final Takeaway for Blogging

A strong blog should not only define each pattern. It should answer:

What problem does this pattern solve?
Where is it used in real projects?
What does the code look like?
When should we avoid it?
How does it improve architecture?
category: system-design

High-Level Design Diagram of Design Patterns Classification

flowchart LR
    A[Design Patterns] --> B[Creational Patterns]
    A --> C[Structural Patterns]
    A --> D[Behavioural Patterns]

    B --> B1[Singleton]
    B --> B2[Factory Method]
    B --> B3[Builder]

    C --> C1[Adapter]
    C --> C2[Decorator]
    C --> C3[Facade]
    C --> C4[Proxy]
    C --> C5[Composite]

    D --> D1[Observer]
    D --> D2[Strategy]
    D --> D3[Command]
    D --> D4[Iterator]
    D --> D5[State]
    D --> D6[Template Method]
    D --> D7[Chain of Responsibility]

Overview of the design pattern categories and their main patterns.

Sequence Diagram: Factory Method Interaction Example

sequenceDiagram
    participant Client
    participant Factory
    participant StripeProcessor
    participant CheckoutProcessor

    Client->>Factory: Create("stripe")
    Factory->>StripeProcessor: instantiate
    Factory-->>Client: returns StripePaymentProcessor

    Client->>StripeProcessor: ProcessPaymentAsync(100)
    StripeProcessor-->>Client: Task completed

    Client->>Factory: Create("checkout")
    Factory->>CheckoutProcessor: instantiate
    Factory-->>Client: returns CheckoutPaymentProcessor

    Client->>CheckoutProcessor: ProcessPaymentAsync(250)
    CheckoutProcessor-->>Client: Task completed

Client interacts with the Factory Method to create and process payments through chosen providers.

Realistic Code Example 1: Composite with Recursive Permission Checks

public interface IPermission
{
    bool IsGranted(string userId);
}

public class UserPermission : IPermission
{
    private readonly HashSet<string> _allowedUsers;

    public UserPermission(IEnumerable<string> allowedUsers)
    {
        _allowedUsers = new HashSet<string>(allowedUsers);
    }

    public bool IsGranted(string userId)
    {
        return _allowedUsers.Contains(userId);
    }
}

public class PermissionGroup : IPermission
{
    private readonly List<IPermission> _permissions = new();

    public void Add(IPermission permission) => _permissions.Add(permission);

    public bool IsGranted(string userId)
    {
        foreach (var permission in _permissions)
        {
            if (permission.IsGranted(userId))
                return true;
        }
        return false;
    }
}

// Usage example:
var readPermission = new UserPermission(new[] { "alice", "bob" });
var writePermission = new UserPermission(new[] { "alice" });

var adminGroup = new PermissionGroup();
adminGroup.Add(readPermission);
adminGroup.Add(writePermission);

Console.WriteLine(adminGroup.IsGranted("alice")); // True
Console.WriteLine(adminGroup.IsGranted("bob"));   // True
Console.WriteLine(adminGroup.IsGranted("eve"));   // False

Notice how both individual permissions and groups implement the same interface, allowing uniform checks recursively.

Realistic Code Example 2: Chain of Responsibility for HTTP Request Processing Pipeline

public abstract class HttpHandler
{
    protected HttpHandler? Next { get; private set; }

    public void SetNext(HttpHandler next)
    {
        Next = next;
    }

    public async Task HandleAsync(HttpContext context)
    {
        if (await ProcessRequestAsync(context) && Next != null)
        {
            await Next.HandleAsync(context);
        }
    }

    protected abstract Task<bool> ProcessRequestAsync(HttpContext context);
}

public class AuthenticationHandler : HttpHandler
{
    protected override Task<bool> ProcessRequestAsync(HttpContext context)
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            context.Response.StatusCode = 401;
            return Task.FromResult(false);
        }
        return Task.FromResult(true);
    }
}

public class LoggingHandler : HttpHandler
{
    protected override Task<bool> ProcessRequestAsync(HttpContext context)
    {
        Console.WriteLine($"Request {context.Request.Path} by {context.User.Identity.Name}");
        return Task.FromResult(true);
    }
}

public class RoutingHandler : HttpHandler
{
    protected override Task<bool> ProcessRequestAsync(HttpContext context)
    {
        Console.WriteLine($"Routing to endpoint for {context.Request.Path}");
        // Simulate handling endpoint
        context.Response.StatusCode = 200;
        return Task.FromResult(false); // No next handler needed
    }
}

// Usage in setup
var authentication = new AuthenticationHandler();
var logging = new LoggingHandler();
var routing = new RoutingHandler();

authentication.SetNext(logging);
logging.SetNext(routing);

// Simulated HttpContext for example
var context = new DefaultHttpContext();
context.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "alice") }, "TestAuth"));
context.Request.Path = "/api/orders";

await authentication.HandleAsync(context);
Console.WriteLine($"Response status code: {context.Response.StatusCode}");

This pattern models the ASP.NET Core middleware pipeline with handlers passing control to the next handler conditionally.

Observability for Design Pattern Implementations

What to Log

  • Factory Method: Log which concrete implementation is created and when.
  • Decorator: Log entering and exiting of decorated methods with timestamps.
  • Facade: Log start and completion of façade methods to trace aggregated workflow.
  • Chain of Responsibility: Log each handler processing or skipping the request and final handling outcome.

Example structured log entry (JSON):

{
  "timestamp": "2024-06-01T10:15:30Z",
  "pattern": "FactoryMethod",
  "factoryName": "PaymentProcessorFactory",
  "productCreated": "StripePaymentProcessor",
  "correlationId": "12345",
  "durationMs": 25
}

Key Metrics (Using RED / USE Frameworks)

PatternRequests/secErrors/secLatency (ms)UtilizationSaturation
Factory MethodRED: Factory usage rateRED: Factory creation errorsRED: Time to create objectsUSE: CPU while creatingUSE: Queue length if async
DecoratorRED: Method calls countRED: Decorator failuresRED: Added latencyUSE: Memory for added cachesUSE: Thread contention
FacadeRED: Facade method callsRED: Subsystem errorsRED: End-to-end latencyUSE: Resource usage across subsystemsUSE: Saturation on integration points
Chain of ResponsibilityRED: Requests passing handlersRED: Errors at each handlerRED: Latency through chainUSE: CPU for middleware logicUSE: Middleware queue depth

Distributed Tracing Snippet (OpenTelemetry in C#)

using OpenTelemetry.Trace;
using OpenTelemetry.Resources;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("DesignPatternsApp"))
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddSource("FactoryMethod", "Decorator", "Facade", "ChainOfResponsibility")
    .AddConsoleExporter()
    .Build();

var tracer = tracerProvider.GetTracer("FactoryMethod");

// Inside factory method creation
using var span = tracer.StartActiveSpan("CreatePaymentProcessor");
try
{
    var processor = factory.Create("stripe");
    span.SetAttribute("processor.type", processor.GetType().Name);
}
catch(Exception ex)
{
    span.RecordException(ex);
    span.SetStatus(Status.Error.WithDescription(ex.Message));
    throw;
}

SLI/SLO Table for Critical Patterns in APIs

SLISLONotes
Factory method success rate≥ 99.9% success in object creationImportant for system stability
Decorator latency overhead< 5ms added per decorationKeep cross-cutting concern overhead low
Facade overall success rate≥ 99.95% successful workflowsFacade must not degrade subsystems' SLAs
Chain of Responsibility latencyp99 latency < 100msEnsure pipeline stays performant

Alerts Worth Paging

  • Factory Method: Repeated failures creating objects (>5/min)
  • Facade: Increased aggregate latency beyond threshold (>200ms p95)
  • Decorator: Exception rate spikes in decorated services (>1% error rate)
  • Chain of Responsibility: Middleware handler failures or timeouts (>1 error/min)