📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are design patterns? Explain the GoF split into creational, structural and behavioural patterns, give a .NET example of each, and tell me when using a pattern makes code worse.

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.

Beginner Theory Beginner behavioural-patterns creational-patterns design-patterns dotnet gof structural-patterns

🎯 Key points

  • A pattern is a named, reusable solution to a recurring design problem: intent, participants, structure and trade-offs, not copy-paste code
  • GoF (1994) catalogue of 23 patterns: creational (how objects are created), structural (how objects are composed), behavioural (how objects collaborate and share responsibility)
  • Creational in .NET: DI singleton/scoped/transient lifetimes, IHttpClientFactory, ILoggerFactory, StringBuilder and WebApplicationBuilder (Builder), ArrayPool<T> (Object Pool)
  • Structural in .NET: GZipStream/BufferedStream wrapping a Stream (Decorator), DelegatingHandler, EF Core lazy-loading proxies (Proxy), ILogger over ILoggerProvider (Bridge)
  • Behavioural in .NET: IEnumerable/yield (Iterator), events and IObservable<T> (Observer), ASP.NET Core middleware (Chain of Responsibility), BackgroundService.ExecuteAsync (Template Method)
  • Patterns give a shared vocabulary: 'wrap it in a decorator' communicates a whole design in four words
  • Modern C# makes some patterns lighter: delegates replace one-method Strategy/Command classes, pattern matching replaces many Visitors, DI replaces hand-rolled Singletons and factories
  • A pattern is ceremony when it adds indirection without a second implementation, a real variation point or a testability need (YAGNI)

⏱ 30-second answer

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:

  • Creational: how objects are created (Singleton, Factory, Builder). In .NET: DI lifetimes, IHttpClientFactory, WebApplicationBuilder.
  • Structural: how objects are composed (Adapter, Decorator, Proxy). In .NET: GZipStream wrapping a Stream, DelegatingHandler.
  • Behavioural: how objects collaborate (Strategy, Observer, Iterator). In .NET: 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IHttpClientFactory and WebApplicationBuilder are a factory and a builder. GZipStream wrapping a FileStream is a Decorator, and so is a DelegatingHandler in an HttpClient pipeline. foreach over IEnumerable is the Iterator pattern, C# events are Observer, and ASP.NET Core middleware is Chain of Responsibility. Modern C# also makes some patterns much lighter: a Func<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 IOrderProcessorFactory with 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."


The three GoF groups (and what came after)

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

What a pattern description contains

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

When a pattern helps vs when it is ceremony

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)

Production example

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].

🔍 What the interviewer is checking

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

  • Defines a pattern by intent and trade-offs, not by code.
  • Names the three groups correctly with a framework example for each.
  • Mentions that DI, delegates and pattern matching make some patterns lighter.
  • Brings up over-engineering unprompted.

Red flags

  • Lists pattern names without being able to say what problem any of them solves.
  • Believes more patterns mean better design.
  • Can't give a single example from the .NET framework.

📚 Learn in depth

1. Where patterns come from

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).

2. Two principles behind almost every GoF pattern

The book states two principles that explain most of the catalogue:

  1. Program to an interface, not an implementation. Clients depend on an abstraction, so implementations can vary (Strategy, Factory, Bridge).
  2. Favour object composition over class inheritance. Behaviour is assembled from objects at run time instead of fixed in a hierarchy (Decorator, Strategy, Composite).
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.

3. Patterns the .NET framework already implements

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

4. How modern C# changes the catalogue

  • Delegates and lambdas: a one-method Strategy or Command is just Func<T, TResult> or Action.
  • Pattern matching and switch expressions: closed hierarchies can be handled without Visitor's double dispatch.
  • Records and with: Prototype-style copying is built into the language (shallow).
  • Dependency injection: Singleton, Factory and much of Abstract Factory become registration choices.
  • 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#.

5. The cost of a pattern

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?"

Try it yourself

  1. Open an ASP.NET Core Program.cs and label every pattern you can find (Builder, DI lifetimes, middleware chain).
  2. Write new GZipStream(new BufferedStream(File.OpenWrite("x.gz")), CompressionLevel.Optimal) and draw the decorator chain.
  3. Use "Go to Definition" on BackgroundService and find the Template Method (StartAsync calls your ExecuteAsync).
  4. Find a class in your codebase with an interface that has exactly one implementation and no test double. Decide whether the interface earns its keep.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Treating patterns as code to copy from a book. Why it is wrong: The value is the intent and trade-offs; the same structure (a wrapper) can be a Decorator, Proxy or Adapter depending on why it exists. Instead: Name the problem first, then pick the pattern whose intent matches.
  • Mistake: Adding an interface and a factory for every class "for flexibility". Why it is wrong: One implementation and no test seam means pure indirection; readers jump through files for nothing. Instead: Introduce the abstraction when the second implementation or a real test need appears.
  • Mistake: Hand-writing a Singleton or factory that the DI container already provides. Why it is wrong: Static state hides dependencies, breaks tests and ignores the container's lifetime and disposal management. Instead: Use AddSingleton, factory delegates or keyed services.
  • Mistake: Using a full class hierarchy where a delegate or a 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.
  • Mistake: Thinking patterns only belong to old-style OOP. Why it is wrong: Middleware, 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.
  • Mistake: Naming classes after patterns (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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says patterns can make code worse Why: Checks judgement about when an abstraction earns its keep
    How to answer

    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.

  2. When: Candidate mentions composition or wrapping objects Why: Checks the 'favour composition over inheritance' principle behind most GoF patterns
    How to answer

    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.

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me