Enterprise-Level Design Patterns in C#

Advanced Updated November 16, 2024

🏗️ 10. Enterprise-Level Design Patterns in C#

🔹 Singleton Pattern

public sealed class Logger
{
    private static readonly Logger _instance = new Logger();
    public static Logger Instance => _instance;
    private Logger() {}
}

🔹 Strategy Pattern

interface ICompression
{
    void Compress(string file);
}

class ZipCompression : ICompression
{
    public void Compress(string file) => Console.WriteLine("ZIP");
}

class Compressor
{
    private ICompression _strategy;
    public Compressor(ICompression strategy) => _strategy = strategy;
    public void Execute(string file) => _strategy.Compress(file);
}

🔹 Factory Pattern

abstract class Vehicle {}
class Car : Vehicle {}
class Bike : Vehicle {}

class VehicleFactory
{
    public Vehicle Create(string type) => type switch
    {
        "car" => new Car(),
        "bike" => new Bike(),
        _ => throw new ArgumentException()
    };
}

📌 Summary: Expert-Level C# Cheat Sheet

+--------------------------+---------------------------------------------------+
| Concept                  | Syntax / Example                                  |
+--------------------------+---------------------------------------------------+
| Generic Constraints      | where T : class, new()                            |
| Reflection               | type.GetProperties(), method.Invoke()            |
| Dynamic Typing           | dynamic obj = GetSomething();                    |
| Parallel Execution       | Parallel.ForEach(items, action)                  |
| IAsyncEnumerable         | await foreach (var i in GetAsync())              |
| Span<T>                  | Span<byte> buffer = stackalloc byte[1024];       |
| Expression Trees         | Expression<Func<int, int>> exp = x => x * x;     |
| Custom Attribute         | [Author("Name")] class MyClass { }               |
| Dependency Injection     | services.AddTransient<IFoo, Foo>();              |
| Source Generators        | Implement ISourceGenerator                        |
| Singleton Pattern        | Logger.Instance                                   |
+--------------------------+---------------------------------------------------+