Patterns and alternatives
Patterns and alternatives
A design pattern names a recurring collaboration between components. Choose it for the problem it solves, not because a project needs a certain number of patterns.
Strategy replaces an algorithm behind a shared contract; a delegate often suffices for a single operation. Factory centralizes construction decisions, while Builder assembles a complex object in steps (and must validate the final result). Adapter translates a mismatched interface; Decorator preserves the interface while adding behavior such as timing or validation. Observer distributes notifications to subscribers, which introduces ordering, exception and subscription-lifetime questions. Command packages a request as data or an object, not necessarily a durable queue. Facade provides a simpler entry point to a subsystem; Composite treats a tree of leaves and groups uniformly. These are object-level design patterns, distinct from architectural patterns and DI containers. In a simple branch with two known formats, a switch is often easier to inspect than a factory hierarchy. Avoid global state hidden behind a Singleton and generic repositories that obscure query capabilities or transaction ownership. Test the behavior of each collaboration, especially ordering and failure. The following formatters use plain synthetic text; the CSV-like format is deliberately limited to integers and is not a general CSV escaping library.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Offline models and multi-project labs are explicitly distinguished.
Use a delegate as a lightweight strategy
Inject the operation instead of building a class hierarchy for one method. A direct switch would also work if callers never supply behavior.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;using System.Linq;int[] values = [2, 4];Console.WriteLine(Render(values, a => string.Join(",", a)));Console.WriteLine(Render(values, a => string.Join(" | ", a.Select(n => $"#{n}"))));static string Render(int[] values, Func<int[], string> format) => format(values);Expected result (not executed):
2,4#2 | #4The function is the strategy. Do not retain or mutate the caller-owned array in this contract. For a stateful formatter with multiple related operations a class can be more appropriate.
Combine an adapter, a factory and a decorator
The old component accepts an integer and returns a legacy label. The adapter exposes the new formatter contract; the decorator surrounds successful output.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;IFormatter plain = Create("legacy");IFormatter decorated = new Brackets(plain);Console.WriteLine(plain.Format(7));Console.WriteLine(decorated.Format(7));try { Create("unknown"); } catch (ArgumentException) { Console.WriteLine("unknown format"); }static IFormatter Create(string kind) => kind switch { "legacy" => new LegacyAdapter(new Legacy()), "number" => new NumberFormatter(), _ => throw new ArgumentException("Unknown format", nameof(kind))};interface IFormatter { string Format(int n); }sealed class Legacy { public string Label(int n) => $"item-{n}"; }sealed class LegacyAdapter(Legacy old) : IFormatter { public string Format(int n) => old.Label(n); }sealed class NumberFormatter : IFormatter { public string Format(int n) => n.ToString(System.Globalization.CultureInfo.InvariantCulture); }sealed class Brackets(IFormatter inner) : IFormatter { public string Format(int n) => "[" + inner.Format(n) + "]"; }Expected result (not executed):
item-7[item-7]unknown formatAdapter changes the contract, whereas Decorator keeps IFormatter. Unknown factory input fails explicitly. Brackets is acceptable only if the caller permits decorated output; it is not transparent under an exact-format promise.
Observe a notification and unsubscribe
A synchronous event demonstrates Observer. Store the delegate to unsubscribe the exact handler.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;var stock = new Stock();Action<int> log = n => Console.WriteLine($"remaining {n}");stock.Changed += log;try { stock.Set(3); }finally { stock.Changed -= log; }stock.Set(2);Console.WriteLine("finished");sealed class Stock { public event Action<int>? Changed; public void Set(int n) { if (n < 0) throw new ArgumentOutOfRangeException(nameof(n)); Changed?.Invoke(n); }}Expected result (not executed):
remaining 3finishedThis toy publisher emits a value without persistence. In synchronous multicast invocation a throwing handler can stop later handlers; choose an explicit failure policy rather than silently ignoring errors. Unsubscription also matters for objects with different lifetimes.
Apply the concept
Design a formatter for a third output style and a validation wrapper. Decide whether to retain a factory, strategy class or delegate.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Patterns and alternatives — knowledge check
Apply the lesson concepts to the following scenarios.
Which pattern changes an incompatible interface into the expected one?
What distinguishes a Decorator from an Adapter?
When should a factory reject an unknown format?
Why store the delegate used for an event subscription?
Two fixed formats never vary externally. What is a reasonable starting design?