Skip to content
Tutorials Center
My learning

Topics

Lesson 158 of 182 ยท Testing and Quality

Design Patterns in C#

Learn the design patterns C# developers use daily - strategy, observer, factory, builder, decorator, adapter, repository, singleton via DI and mediator - with short runnable examples and advice on when not to use them.

A design pattern is a named, proven solution to a problem that keeps appearing in software design. It is not a library you install or a piece of code you copy. It is a shape: "put the varying part behind an interface and pass it in" is the Strategy pattern, whether you write it with a class, a lambda or a generic. The value of patterns is mostly vocabulary. When a teammate says "wrap it in a decorator" you immediately know the design, and when you read a codebase you recognize the moving parts.

Modern C# changes how patterns look. Delegates and lambdas replace many one-method interfaces, events are the built-in Observer, records with with copy objects, and the dependency-injection container manages object lifetimes so you rarely write a hand-made singleton. This lesson walks through the nine patterns you will meet most often in .NET code, each with a short runnable example, and ends with advice on when not to use them.

Before this lesson you should be comfortable with interfaces and polymorphism, delegates, events and dependency injection.

Strategy: swap an algorithm

Problem: a class contains if/switch logic that chooses between several ways of doing one job (shipping cost, discount rules, sorting order), and every new variant means editing that class.

Solution: move each variant behind a common abstraction, and let the caller pass the one it wants. The class that uses it no longer knows or cares which variant it got.

In C# the abstraction is often just a delegate (Func<...>), because a strategy is usually one function. When the strategy has several methods or needs state, use an interface.

C# Strategy with an interface and with a delegate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Adding "pickup point" shipping now means adding one class; nothing that uses IShippingStrategy changes. This is the open/closed principle: open for extension, closed for modification. FreeOverLimit also shows that strategies can be combined by wrapping one another (a hint of the Decorator below).

Use it when you have several interchangeable algorithms chosen at run time or by configuration. Avoid it for two variants that will never grow: a plain if is clearer.

Factory: hide how objects are created

Problem: the code that needs an object should not need to know which concrete class to build, how to construct it, or what its dependencies are.

Solution: put creation behind a method or object. Forms you will see:

  • A static factory method (Money.FromCents(1250), Task.FromResult, TimeSpan.FromSeconds): named constructors with clear intent.
  • A factory class or delegate that decides which subtype to create from input.
  • The DI container, which is a general-purpose factory.
C# A factory chooses the concrete type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Callers depend only on IFileParser. Supporting .xml is one new dictionary entry. When the creators need dependencies (a logger, a connection), let the DI container build them, as shown in the repository section below. Note the classic Abstract Factory (a factory of related factories) is rarely worth the ceremony in C#: a few delegates or DI registrations do the same job.

Observer: tell me when something happens

Problem: one object changes and several others need to react, without the first knowing who they are (a button and its handlers, a price feed and its subscribers).

Solution: the subject keeps a list of subscribers and notifies them. C# builds this into the language as events: the publisher declares an event, subscribers attach handlers with += and detach with -=. See events for the full story.

C# Observer with events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The feed never mentions PriceAlert; anything can listen. Three pitfalls come up again and again:

  • Memory leaks: the publisher's event holds a reference to every subscriber. A short-lived subscriber on a long-lived publisher must unsubscribe (or the publisher must use weak references).
  • Exceptions: one throwing handler stops the remaining handlers from running. Catch inside handlers or invoke them one by one if that matters.
  • Order and threads: handlers run synchronously on the caller's thread, in subscription order (though that order is not a contract you should depend on).

For asynchronous streams of data, look at IObservable<T> (Reactive Extensions), channels and async streams.

Builder: construct complex objects step by step

Problem: an object needs many optional parts, and a constructor with ten parameters (half of them null) is unreadable.

Solution: a builder collects settings through readable method calls and produces the finished object at the end. You use this pattern constantly without noticing: WebApplication.CreateBuilder, StringBuilder, HostBuilder.

Modern C# also gives you cheaper tools: optional and named parameters, required and init properties, and records with with expressions. Reach for a builder when construction has steps, validation across fields, or fluent configuration:

C# A fluent builder that validates on Build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The builder is mutable while it collects settings, but what it produces (HttpRequestSpec) is an immutable record. Validation happens in one place, Build, so an invalid object can never exist. (Notice the pattern _method is "GET" or "HEAD" inside the condition; see pattern matching.)

Decorator: add behavior by wrapping

Problem: you want to add behavior (logging, caching, retries, timing, authorization) to an existing service without changing it or creating a subclass for every combination.

Solution: write a class that implements the same interface, holds an inner instance and delegates to it, adding its own work before or after. Because the decorator is an IPriceService too, callers cannot tell the difference, and decorators stack like layers.

C# Stacking decorators around a service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second call to apple skips the database line: the cache layer answered. The order of wrapping matters; if logging were the inner layer it would not see cached calls. ASP.NET Core's middleware pipeline is this pattern applied to requests, and HttpClient message handlers (DelegatingHandler) are decorators around the network call. Remember that decorators for a stateful wrapper (the cache above) must be registered with the right lifetime in DI.

Adapter: make an incompatible class fit

Problem: you have a class with a useful job but the wrong interface, usually from a library or legacy code you cannot change.

Solution: write a small class that implements the interface your code expects and translates calls to the other class. Adapters are also the right way to protect your code from a third-party API, as recommended in mocks and fakes: wrap it once and the rest of your program stays independent.

C# An adapter around a legacy class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The adapter hides the unit conversion and the weird raw reading. Extension methods (extension methods) are a lighter way to adapt a type's shape when you only need extra methods, not a new interface.

Repository: a collection-like door to data

Problem: business code is full of SQL or ORM calls, which makes it hard to read and impossible to test without a database.

Solution: hide data access behind an interface that looks like a collection of aggregates: Get(id), Add(item), FindByEmail(...). Business code talks to IOrderRepository; one implementation uses a database, another (a fake) uses memory for tests. See repositories and unit of work for the full discussion, including the honest question of whether an ORM like Entity Framework already is a repository.

Singleton: one instance, but let the container hold it

Problem: some objects should exist only once per application: configuration, a cache, a connection pool, a clock.

The classic approach is a class with a private constructor and a static Instance property. It works, but it creates hidden global state: code can reach it from anywhere, tests cannot replace it, and you must reason about thread safety yourself.

The modern approach is to write an ordinary class and register it with the singleton lifetime in the DI container. The container creates it once and hands out the same instance to everyone who asks, and tests can register a different one.

C# Singleton lifetime through DI, and the repository registered next to it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ISequence was registered as a singleton, so both services share one counter (ids 1 and 2), while each transient repository is separate (each service sees only its own customer). This is how repository, factory and singleton cooperate in a typical application: the container is the factory, the lifetime is the singleton, and the interface is the seam. See dependency injection for scoped and transient lifetimes.

A singleton that holds mutable state is shared by all threads of the application, so it must be thread-safe (note the Interlocked.Increment above). Also, never let a singleton depend on a scoped service (for example a per-request database context); that "captive dependency" keeps the scoped object alive forever.

Mediator: one object coordinates the requests

Problem: many components call each other directly, creating a web of dependencies. Controllers need ten services each.

Solution: components send messages (requests) to a mediator, which finds the one handler responsible and returns its result. The sender knows only the request type; the handler knows only its own job. This is the idea behind libraries such as MediatR (a NuGet package, so not available in the editor) and the CQRS style (commands that change data, queries that read it). A minimal version is short:

C# A tiny mediator built on DI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The caller writes mediator.Send(new AddNumbers(20, 22)) and never mentions AddNumbersHandler. The cost is indirection: finding "who handles this" needs a search, stack traces get longer, and a mediator over a small app can be pure overhead. A real library adds async handlers, notifications to many handlers and pipeline behaviors (which are decorators, again).

Choosing patterns wisely

  • Patterns are a vocabulary, not a goal. Start with the simplest code that works. When you notice a specific pain (a growing switch, duplicated wrapping logic, untestable construction), the matching pattern is the cure.
  • Prefer language features first. Delegates for strategies, events for observers, with expressions for copying, records for value objects, DI for singletons and factories, extension methods for light adapters.
  • Favor composition over inheritance. Strategy, decorator, adapter and mediator all combine objects instead of building deep class hierarchies (inheritance, object design).
  • Too many layers is a smell. An IUserServiceFactoryProviderManager solving no real problem is the usual result of using patterns for decoration. Every abstraction must pay for itself with a second implementation, a test seam or a clearer boundary.
  • Name classes after their role (CachingPriceService, ShippingStrategy): the pattern name in the class name helps readers.

Patterns not covered here, but worth knowing by name: Template Method (a base class defines the skeleton and subclasses fill steps), Command (an action as an object, enabling undo and queues), State (behavior changes with an internal state object), Chain of Responsibility (middleware), Proxy (a stand-in controlling access), Facade (a simple front for a complex subsystem) and Specification (a reusable, combinable rule). Good places to meet them in .NET: middleware, DelegatingHandler, ILogger providers, IEnumerable (iterator pattern, see iterators and yield) and the Stream decorators such as GZipStream wrapping another stream.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A CachingPriceService implements IPriceService and wraps another IPriceService. Which pattern is this?

    A decorator implements the same interface as the object it wraps and adds behavior around the delegated call. An adapter changes the interface instead.
  2. 2. Which C# feature is the built-in implementation of the Observer pattern?

    An event lets subscribers attach with += and detach with -=, and the publisher notifies all of them without knowing who they are.
  3. 3. Why is registering a class as a singleton in the DI container usually better than a hand-written static Instance property?

    The container still gives you one shared instance, but the dependency is explicit and replaceable, instead of hidden global state.
  4. 4. You wrap a third-party library class so the rest of your program calls your own interface. Which pattern, and what benefit?

    An adapter translates between interfaces. Keeping the library behind your own interface also makes the code easier to test and to switch later.
  5. 5. When is a builder better than a constructor with optional parameters?

    A builder shines for many optional pieces, fluent configuration and a single Build step that validates and creates the finished object.

Summary

  • A design pattern is a named solution shape; its main value is shared vocabulary.
  • Strategy swaps an algorithm (interface or delegate); Factory hides creation; Observer is C# events; Builder assembles complex objects step by step.
  • Decorator adds behavior by wrapping the same interface; Adapter converts an interface; Repository hides data access behind a collection-like interface.
  • Prefer a singleton lifetime in the DI container to a hand-written static instance, and make singleton state thread-safe.
  • Mediator routes requests to handlers so components stay decoupled, at the price of indirection.
  • Use language features first, favor composition over inheritance, and add a pattern only when it solves a real problem.

Next: Source Generators and Roslyn