Design patterns in C#
Design patterns are named, tested solutions to design problems that keep coming back. Using one online-shop checkout, this note covers Strategy, Factory, Builder, Decorator, Adapter, Observer, Singleton (Lazy<T> vs AddSingleton) and the Result pattern.
71.1 The problem: everything in one method
- PlaceOrder takes an amount and a coupon code; a switch applies the discount and the method itself does new SmsSender().
- Every new coupon means editing the switch (violates Open/Closed).
- The SMS sender is hard-coded inside, so it cannot be swapped or faked in a test.
- A normal business case (unknown coupon) throws an exception and crashes the app.
PlaceOrder(2000m, "FLAT100");PlaceOrder(1500m, "DIWALI20"); void PlaceOrder(decimal amount, string code){ var total = code switch { "FLAT100" => amount - 100, "SALE10" => amount * 0.9m, _ => throw new ArgumentException( $"Unknown coupon {code}") }; new SmsSender().Send($"Paid Rs {total}");}$ dotnet run bug.csSMS: Paid Rs 1900Unhandled exception. System.ArgumentException:Unknown coupon DIWALI20- Step 1
1.Coupon switch: every new coupon = edit this method
- Step 2
2.new SmsSender(): dependency hard-coded inside
- Step 3
3.DIWALI20 not in the switch -> ArgumentException
- Step 4
4.Normal business case becomes an app crash
- Step 5
5.Fix: patterns split creation, behaviour and failure handling
SOLID says what to aim for; patterns say how
71.2 Strategy: one class per discount
- Different ways of doing one job go into different classes behind one interface.
- The caller only knows IDiscount; FlatOff and PercentOff are interchangeable.
- A new discount = a new class, no edit to existing code.
- The IPaymentMethod from the SOLID video was this pattern without the name.
interface IDiscount{ decimal Apply(decimal amount);}class FlatOff(decimal off) : IDiscount{ public decimal Apply(decimal a) => a - off;}class PercentOff(int pct) : IDiscount{ public decimal Apply(decimal a) => a * (100 - pct) / 100;}71.3 Factory: creation in one place
- DiscountFactory.Create turns a coupon string into the right IDiscount.
- ToUpperInvariant() makes the code case-insensitive; an unknown code returns null.
- The switch still exists, but only in one place instead of inside business logic.
string[] codes = ["FLAT100", "SALE10"];foreach (var code in codes) Console.WriteLine(DiscountFactory .Create(code)?.Apply(2000m)); static class DiscountFactory{ public static IDiscount? Create(string code) => code.ToUpperInvariant() switch { "FLAT100" => new FlatOff(100), "SALE10" => new PercentOff(10), _ => null };}$ dotnet run factory.cs1900180071.4 Builder: an order step by step
- Use it when an object has many optional parts (items, coupon, gift wrap) and a big constructor gets confusing.
- Every step returns the builder itself, so calls chain fluently.
- Build() does the final validation: an order without items throws InvalidOperationException, so an incomplete object never gets out.
var order = new OrderBuilder() .AddItem("Mixer Grinder", 2499m) .AddItem("Steel Bottle", 399m) .WithCoupon("FLAT100") .WithGiftWrap() .Build();Console.WriteLine(order); // inside class OrderBuilderpublic Order Build() => items.Count > 0 ? new(items.Count, items.Sum(i => i.Price), coupon, giftWrap) : throw new InvalidOperationException( "Order needs at least one item");$ dotnet run builder.csOrder { Items = 2, Total = 2898, Coupon = FLAT100, GiftWrap = True } # new OrderBuilder().WithGiftWrap().Build()Unhandled exception.System.InvalidOperationException:Order needs at least one item71.5 Decorator: add behaviour by wrapping
- LoggingNotifier implements INotifier and wraps another INotifier.
- It writes the log line and then passes the call to the inner notifier.
- SmsNotifier is not touched; decorators can be stacked (e.g. Logging around Retry around Sms).
INotifier notifier = new LoggingNotifier(new SmsNotifier());notifier.Send("Order 101 placed"); class LoggingNotifier(INotifier inner) : INotifier{ public void Send(string msg) { Console.WriteLine($"[log] {msg}"); inner.Send(msg); }}$ dotnet run decorator.cs[log] Order 101 placedSMS: Order 101 placed- Step 1
1.Caller calls notifier.Send("Order 101 placed")
- Step 2
2.LoggingNotifier writes [log] Order 101 placed
- Step 3
3.LoggingNotifier calls inner.Send(msg)
- Step 4
4.SmsNotifier sends SMS: Order 101 placed
Same interface outside, extra behaviour inside
71.6 Adapter: make a third-party SDK fit
- The old LegacyPayClient takes paise and returns a status string; we cannot change it.
- Our code wants IPaymentGateway.Pay(decimal rupees) returning bool.
- The adapter converts rupees to paise, calls the SDK and maps "SUCCESS" to true, like a travel plug adapter.
IPaymentGateway gateway = new LegacyPayAdapter(new LegacyPayClient());Console.WriteLine(gateway.Pay(1899.50m)); class LegacyPayAdapter(LegacyPayClient client) : IPaymentGateway{ public bool Pay(decimal rupees) { var paise = (long)(rupees * 100); var status = client.Charge(paise); return status == "SUCCESS"; }}$ dotnet run adapter.csLegacyPay: charging 189950 paiseTrue71.7 Observer: events in C#
- When an order is placed, stock and email must react, but OrderService must not know about them.
- In C# the Observer pattern is simply an event: subscribers use +=, the publisher calls Invoke.
- ?.Invoke avoids a NullReferenceException when nobody has subscribed.
var orders = new OrderService();orders.OrderPlaced += id => Console.WriteLine($"Stock updated: {id}");orders.OrderPlaced += id => Console.WriteLine($"Email sent: {id}");orders.Place("ORD-101"); class OrderService{ public event Action<string>? OrderPlaced; public void Place(string id) => OrderPlaced?.Invoke(id);}$ dotnet run observer.csStock updated: ORD-101Email sent: ORD-10171.8 Singleton with Lazy<T>
- Singleton = only one object of a class in the whole app.
- A private constructor stops anyone outside from calling new.
- Lazy<AppConfig> creates the object only when .Value is first read, and it is thread-safe by default.
- Output shows Loading config... after App started (lazy) and True (same object both times).
Console.WriteLine("App started");Console.WriteLine(AppConfig.Instance.DeliveryFee);Console.WriteLine(ReferenceEquals( AppConfig.Instance, AppConfig.Instance)); sealed class AppConfig{ static readonly Lazy<AppConfig> instance = new(() => new AppConfig()); public static AppConfig Instance => instance.Value; public decimal DeliveryFee { get; } = 49m; private AppConfig() => Console.WriteLine("Loading config...");}$ dotnet run singleton.csApp startedLoading config...49TrueCheckpoint: 100 threads read Instance at the same time. Loading config... prints only once, because Lazy<T> uses a lock by default. A hand-made 'if (instance == null) instance = new ...' can create two objects under races.
Parallel.For(0, 100, _ =>{ var config = AppConfig.Instance;});Console.WriteLine("Done");$ dotnet run checkpoint.csLoading config...Done71.9 Comparison: hand-made Instance vs AddSingleton
// Wrong: hidden dependencyclass OrderService{ public decimal Total(decimal amount) => amount + AppConfig.Instance.DeliveryFee;}// hidden dependency, fee fixed in tests// Right: one object, from DI, testablebuilder.Services.AddSingleton<IAppConfig, AppConfig>(); class OrderService(IAppConfig config){ public decimal Total(decimal amount) => amount + config.DeliveryFee;}| Point | AppConfig.Instance (static) | AddSingleton (DI) |
|---|---|---|
| Objects in the app | One | One (the container keeps it) |
| Dependency | Hidden inside the method | Visible in the constructor |
| Testing | Cannot change the delivery fee | Pass a fake IAppConfig easily |
| Verdict | Avoid in services | Preferred |
71.10 Result pattern instead of exceptions
- An invalid coupon is an expected business case, not an unexpected error.
- Return Result<T> with Value and Error; IsSuccess is true when Error is null.
- A null from the factory becomes an error Result; no crash, the caller decides what to show.
- Keep exceptions for truly unexpected failures (DB down, bug).
var ok = Checkout(2000m, "FLAT100");var bad = Checkout(2000m, "OOPS");Console.WriteLine($"{ok.IsSuccess} {ok.Value}");Console.WriteLine($"{bad.IsSuccess} {bad.Error}"); Result<decimal> Checkout(decimal amount, string code){ var offer = DiscountFactory.Create(code); return offer is null ? new(0, $"Invalid coupon {code}") : new(offer.Apply(amount), null);}record Result<T>(T? Value, string? Error){ public bool IsSuccess => Error is null; }$ dotnet run result.csTrue 1900False Invalid coupon OOPS71.11 Three families of patterns
| Family | Decides | Patterns in this video |
|---|---|---|
| Creational | How an object gets created | Factory, Builder, Singleton |
| Structural | How objects connect to each other | Decorator, Adapter |
| Behavioral | How objects share the work | Strategy, Observer |
71.12 When to use which
| You see... | Use |
|---|---|
| A long switch on a type or code | Strategy + Factory |
| Many optional parts plus validation | Builder |
| Need extra behaviour without changing a class | Decorator |
| A third-party API with the wrong shape | Adapter |
| Many listeners for one happening | Observer (event) |
| Exactly one shared object | AddSingleton (or Lazy<T> if hand-made) |
| Expected business failure | Result |
71.13 Common mistakes
- Thinking more patterns = better code: every pattern adds a layer; with only one discount a plain method is enough.
- Thinking Singleton is always bad: the problem is static access; a DI singleton is fine.
- Hand-made singleton with a null check: not thread-safe, can create two objects.
- Throwing exceptions for normal business outcomes like an invalid coupon.
71.14 Interview tips
- Answer 'which patterns have you used?' with examples, not a list of names.
- Say: Strategy for discounts with a Factory to create them, Decorator for logging, Adapter for a third-party SDK.
- For a singleton: AddSingleton from DI; Lazy<T> when a hand-made one is really needed (thread-safe).
- Mention that Observer in C# is just events.
- Say you return a Result for expected failures and keep exceptions for unexpected ones.