Design Patterns Made Easy with C# — Pt 1

Harnessing the power of design patterns makes your code readable, elegent and efficient.

Stephen Robert James Adam
2 min readMar 21, 2021

There are lots of great articles on design patterns; unfortunately many of them make them far more complicated than than they need to be.

My aim with this series is to demystify them, refresh my memory of a few and give some real world applications in a concise, code based and approachable way.

A pattern is an idea that has been useful in one practical context and will probably be useful in others.
Martin Fowler

The Adapter Pattern

Description

The adapter pattern is used adapt one class to fit the signature of another. In the example below we have service expecting a Person object with a Name property. How do we handle a FrenchPerson with a Nom property?

Real world uses

A good example would be using a third party dependency injection framework such as Simple Injector with Web Api.

MVC Core comes with its own baked in dependency injection framework, in order to use simple injector with it needs to have a class which implements the frameworks IDependencyResolver. This way SimpleInjector can be treated in exactly the same way as the framework DI container.

The Decorator Pattern

Description

You can think of the decorator as a russian doll, where a class can have it’s behaviour extended and modified at run time. The behaviour have be shared between classes and doesn’t require the modification of the class itself.

Often we’ll want to augment the behaviour of a given set of classes in our system. In the example below we have a QueryExecutor which has logging and caching functionality added at runtime.

Real world uses

The above example was inspired by a very similar real world implemention I wrote for a MediatR implementation. MediatR is a library which can be used to wire a set of commands (or queries) to handlers. Much like the example above I had a number of query handlers I wanted to add logging and error handling to in a generic way.

The Chain of Responsibility Pattern

Similar to the decorator pattern, it differs in that it allows the forwarding of a request until a condition is met or the end of the chain is reached.

Real world uses

The request processing pipeline for ASP.NET Core MVC uses exactly this pattern to handle Http requests and responses.

--

--