What design patterns are, the three GoF categories with .NET framework examples (DI lifetimes, IHttpClientFactory, StringBuilder, Stream wrappers, DelegatingHandler, IEnumerable, middleware), and when a pattern is ceremony.
A design pattern is a named, proven solution to a recurring design problem, described by its intent, participants and trade-offs. It is not a library. The 1994 "Gang of Four" (GoF) book catalogued 23 of them in three groups:
IHttpClientFactory, WebApplicationBuilder.GZipStream wrapping a Stream, DelegatingHandler.IEnumerable/yield, events, middleware.Their biggest value is a shared vocabulary. The trade-off is that every pattern adds indirection, so use one only when it removes a real problem, not because the problem looks similar to a textbook diagram.
"A design pattern is a named solution to a design problem that keeps coming back. It describes the intent, the participants and their relationships, and the trade-offs, so it's closer to a recipe than to code you paste in. The Gang of Four book from 1994 catalogued 23 patterns in three groups. Creational patterns are about how objects get created: Singleton, Factory Method, Abstract Factory, Builder and Prototype. Structural patterns are about how objects are composed into bigger structures: Adapter, Decorator, Proxy, Facade, Composite, Bridge and Flyweight. Behavioural patterns are about how objects collaborate and split responsibility: Strategy, Observer, Command, Iterator, State, Template Method and the rest. Since then the catalogue has grown: Fowler's enterprise patterns like Repository and Unit of Work, messaging patterns like Outbox and Saga, and resilience patterns like Retry and Circuit Breaker are just as common in a .NET service today.
In .NET you use them every day, often without naming them. The DI container's singleton and scoped lifetimes are the creational patterns done for you, and
IHttpClientFactoryandWebApplicationBuilderare a factory and a builder.GZipStreamwrapping aFileStreamis a Decorator, and so is aDelegatingHandlerin anHttpClientpipeline.foreachoverIEnumerableis the Iterator pattern, C# events are Observer, and ASP.NET Core middleware is Chain of Responsibility. Modern C# also makes some patterns much lighter: aFunc<T>is a one-method Strategy, and a switch expression with pattern matching replaces many Visitors.The mistake I see is pattern-first design: an
IOrderProcessorFactorywith one implementation, or a Strategy for two branches that will never grow. Over-applied patterns turn into anti-patterns, like a god Facade or a service locator posing as a factory. Each pattern adds indirection, so I reach for one when I can name the force it resolves, like a second implementation, a real variation point or a test seam. A pattern should make the code easier to change, not just easier to draw."
| Group | Question it answers | Patterns | Where .NET uses it |
|---|---|---|---|
| Creational | Who creates the object, and how? | Singleton, Factory Method, Abstract Factory, Builder, Prototype (+ Object Pool) | DI lifetimes, IHttpClientFactory, ILoggerFactory, DbProviderFactory, StringBuilder, WebApplicationBuilder, ArrayPool<T> |
| Structural | How are objects composed? | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy | Stream wrappers, DelegatingHandler, ILogger/ILoggerProvider, CompositeFileProvider, EF Core proxies, string interning |
| Behavioural | How do objects collaborate? | Strategy, Observer, Command, Mediator, Chain of Responsibility, State, Visitor, Template Method, Iterator, Memento, Interpreter | IComparer<T>, events, IObservable<T>, middleware, ExpressionVisitor, BackgroundService, IEnumerable<T> |
| Enterprise (Fowler, 2002) | How is an application layered? | Repository, Unit of Work, Service Layer, DTO, Data Mapper | DbContext (UoW), DbSet<T> (repository-like), EF Core (Data Mapper) |
| Messaging and resilience | How do services stay correct and available? | Outbox, Inbox, Saga, Retry, Circuit Breaker, Bulkhead | MassTransit, NServiceBus, Polly / Microsoft.Extensions.Http.Resilience |
| Element | Meaning |
|---|---|
| Name | The shared vocabulary ("decorator") |
| Intent | The problem it solves |
| Participants | The roles (Component, ConcreteDecorator…) |
| Structure | How the roles relate |
| Consequences | What you gain and what it costs |
| Helps | Ceremony |
|---|---|
| Two or more real implementations today | "We might need another one later" |
| A cross-cutting concern to add without touching the class (Decorator) | A wrapper that only forwards calls |
| A variation point the business actually changes (pricing rules) | A Strategy for a two-branch if that never changes |
The framework expects it (middleware, IHostedService) |
Re-implementing what DI already does (hand-rolled Singleton) |
A typical over-patterned payments service needed nine files touched to add one field, because every call went through a factory, a facade and a mediator, each with a single implementation. Collapsing the single-implementation layers and keeping the two patterns with real variation (payment-provider Adapters and a retry Decorator) cuts that kind of change from around two days to half a day and removes thousands of lines. In an interview, tell your own version: [a codebase where you removed or added a pattern, and the measurable effect].
Checks that the candidate understands what patterns are for, can map the GoF categories to real .NET code, and has the judgement not to over-apply them.
Green flags
Red flags
The idea comes from the architect Christopher Alexander (A Pattern Language, 1977): recurring problems in buildings have recurring solutions with names. Gamma, Helm, Johnson and Vlissides (the "Gang of Four") applied it to object-oriented software in Design Patterns: Elements of Reusable Object-Oriented Software (1994). Martin Fowler's Patterns of Enterprise Application Architecture (2002) added the enterprise patterns (Repository, Unit of Work, Service Layer, DTO), and later work added messaging patterns (Outbox, Saga) and resilience patterns (Retry, Circuit Breaker, Bulkhead).
The book states two principles that explain most of the catalogue:
Client ──uses──▶ «interface» IComponent
▲ ▲
│ │
ConcreteComponent Decorator ──wraps──▶ IComponent
That one diagram is the skeleton of Decorator, Proxy and Composite. The patterns differ in intent, not shape.
| Pattern | Framework type | What it does |
|---|---|---|
| Singleton | services.AddSingleton<T>() |
One instance per container |
| Factory | IHttpClientFactory.CreateClient(name) |
Creates configured clients, pools handlers |
| Abstract Factory | DbProviderFactory |
Creates a family: connection, command, parameter |
| Builder | WebApplication.CreateBuilder(args) |
Step-by-step configuration, then Build() |
| Object Pool | ArrayPool<T>.Shared |
Reuses buffers to avoid allocations |
| Decorator | GZipStream(innerStream) |
Adds compression to any Stream |
| Proxy | EF Core lazy-loading proxies | Loads navigation properties on first access |
| Iterator | IEnumerable<T> + yield return |
Compiler-generated state machine |
| Observer | event EventHandler<T> |
Publisher notifies subscribers |
| Chain of Responsibility | ASP.NET Core middleware | Each component can handle or pass on |
| Template Method | BackgroundService.ExecuteAsync |
Base class owns the lifecycle, you fill in a step |
Func<T, TResult> or Action.with: Prototype-style copying is built into the language (shallow).IEnumerable and yield: Iterator is a language feature.Peter Norvig observed in 1996 that 16 of the 23 GoF patterns become simpler or invisible in dynamic languages. The same is partly true of modern C#.
Every pattern adds at least one of: an extra type, an interface, a virtual or interface call, an allocation, or a level of indirection when reading the code. Runtime cost is usually nanoseconds and the JIT can often devirtualise sealed types. The real cost is cognitive: a reader must jump through more files to understand one behaviour. That is why the senior question is always "what force does this resolve?"
Program.cs and label every pattern you can find (Builder, DI lifetimes, middleware chain).new GZipStream(new BufferedStream(File.OpenWrite("x.gz")), CompressionLevel.Optimal) and draw the decorator chain.BackgroundService and find the Template Method (StartAsync calls your ExecuteAsync).Three framework patterns you use without naming them:
namespace PatternsTour;
using System.IO.Compression;
public static class Tour
{
// Builder: configure step by step, then Build()
public static WebApplication CreateApp(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(TimeProvider.System); // Singleton via DI, not a static Instance
builder.Services.AddHttpClient("catalogue"); // Factory: IHttpClientFactory creates and pools handlers
return builder.Build();
}
// Decorator: each stream adds behaviour to the one it wraps
public static async Task WriteCompressedAsync(string path, byte[] data, CancellationToken ct)
{
await using FileStream file = File.Create(path);
await using var buffered = new BufferedStream(file); // adds buffering
await using var gzip = new GZipStream(buffered, CompressionLevel.Optimal); // adds compression
await gzip.WriteAsync(data, ct);
}
// Iterator: the compiler turns yield into a state machine implementing IEnumerator<T>
public static IEnumerable<int> Evens(int max)
{
for (int i = 0; i <= max; i += 2)
yield return i;
}
// Strategy without a class hierarchy: a delegate is a one-method strategy
public static decimal Price(decimal amount, Func<decimal, decimal> discount) => discount(amount);
}
AddSingleton, factory delegates or keyed services.switch expression is clearer. Why it is wrong: Five classes for five one-line rules is harder to read than a five-arm switch. Instead: Use Func<> or pattern matching until the rules gain state or dependencies.IEnumerable, IHttpClientFactory and DelegatingHandler are patterns in the newest .NET APIs. Instead: Recognise them so you can extend the framework the way it was designed.OrderStrategyFactoryManager). Why it is wrong: The name describes mechanics, not the domain, and signals pattern-first design. Instead: Name by role in the domain (ShippingCostCalculator), and mention the pattern in a comment or ADR if useful.A senior engineer treats patterns as vocabulary and options, not goals. The skill interviewers look for is recognising when a problem has the forces a pattern resolves, and noticing that the framework has already solved it. In a modern .NET 10 service most creational patterns are DI registration choices, many structural patterns are DI decorators or DelegatingHandlers, and many behavioural patterns are delegates, IEnumerable and pattern matching. In cloud services the patterns with the biggest payoff are usually the newer ones: Retry, Circuit Breaker and Bulkhead around every remote call, and Outbox/Inbox wherever a database write and a message must agree. Concurrency also changes the calculus. Shared objects such as singletons, flyweights and pools must be thread-safe or immutable, which is often a stronger reason to choose immutable records than any pattern.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Plain code (if/switch, a function) |
One implementation, stable rules | None | Rules change often or need their own dependencies |
Delegate (Func<>) |
One-method variation, no state | Tiny | Variation needs several methods, state or DI |
| GoF pattern with types | Several real implementations, a variation point, a test seam | Extra types, indirection | Speculative future needs |
Framework mechanism (DI, middleware, DelegatingHandler) |
The framework already models it | Learning the framework | Never re-implement it by hand |
| Anti-pattern | What it looks like | Pattern it is mistaken for |
|---|---|---|
| Service Locator | sp.GetService<T>() inside business code |
Factory |
| God object | A *Facade or *Manager with 40 methods |
Facade |
| Speculative generality | Interfaces with one implementation "for later" | Strategy / Abstract Factory |
| Poltergeist | A class that only forwards calls | Proxy / Mediator |
To judge whether a pattern earned its keep, I look at change cost: how many files a typical change touches, how long new joiners take to trace a request, and whether the abstraction has more than one implementation in production or tests.
I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.
Default to composition: build behaviour from small objects behind interfaces and inject them. It keeps coupling low, lets behaviour change at run time and is easy to test. Use inheritance only when all of these hold: there is a true is-a relationship where every subtype can substitute for the base (Liskov), the base was designed for extension (documented virtual hooks, protected constructor), there is one axis of variation, and you want to share state plus a fixed algorithm (template method). Framework extension points such as BackgroundService, DelegatingHandler and DbContext are good inheritance cases. When a hierarchy explodes or subclasses override things to throw NotSupportedException, refactor by extracting the varying behaviour into strategies and composing them.
Last updated 18 Nov 2026.