Introduction

Design patterns are proven solutions to common software design problems. They help you write:

In modern development with .NET 9, design patterns are widely used in:

🧠 What Are Design Patterns?

Design patterns are templates or best practices, not ready-made code.

👉 They solve problems like:

🔷 Types of Design Patterns

1. Creational Patterns

👉 Handle object creation

2. Structural Patterns

👉 Organize classes and objects

3. Behavioral Patterns

👉 Manage communication

🔥 Most Useful Patterns in .NET 9 (with Examples)

🔹 1. Singleton Pattern

📌 Use Case

✅ Example

public class Logger
{
    private static Logger _instance;

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Logger();

            return _instance;
        }
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

💡 .NET 9 Best Practice

👉 Use Dependency Injection instead:

builder.Services.AddSingleton<Logger>();

🔹 2. Factory Pattern

📌 Use Case

✅ Example

public interface INotification
{
    void Send();
}

public class EmailNotification : INotification
{
    public void Send() => Console.WriteLine("Email Sent");
}

public class SmsNotification : INotification
{
    public void Send() => Console.WriteLine("SMS Sent");
}

public class NotificationFactory
{
    public static INotification Create(string type)
    {
        return type switch
        {
            "email" => new EmailNotification(),
            "sms" => new SmsNotification(),
            _ => throw new Exception("Invalid type")
        };
    }
}

🔹 3. Repository Pattern

📌 Use Case

✅ Example

public interface IProductRepository
{
    Task<Product> GetById(int id);
}

public class ProductRepository : IProductRepository
{
    public async Task<Product> GetById(int id)
    {
        // DB logic here
        return new Product();
    }
}

👉 Register in .NET 9:

builder.Services.AddScoped<IProductRepository, ProductRepository>();

🔹 4. Dependency Injection (DI)

📌 Built-in in .NET 9

👉 Core of modern .NET apps

public class OrderService
{
    private readonly IProductRepository _repo;

    public OrderService(IProductRepository repo)
    {
        _repo = repo;
    }
}

⚡ Benefit

🔹 5. Strategy Pattern

📌 Use Case

✅ Example

public interface IPaymentStrategy
{
    void Pay();
}

public class CreditCardPayment : IPaymentStrategy
{
    public void Pay() => Console.WriteLine("Paid via Credit Card");
}

public class UpiPayment : IPaymentStrategy
{
    public void Pay() => Console.WriteLine("Paid via UPI");
}

👉 Usage:

public class PaymentContext
{
    private readonly IPaymentStrategy _strategy;

    public PaymentContext(IPaymentStrategy strategy)
    {
        _strategy = strategy;
    }

    public void Execute() => _strategy.Pay();
}

🔹 6. Observer Pattern

📌 Use Case

✅ Example (using events)

public class Publisher
{
    public event Action OnChange;

    public void Notify()
    {
        OnChange?.Invoke();
    }
}

🔹 7. Mediator Pattern (Used in CQRS)

👉 Common with libraries like MediatR

📌 Use Case

public class CreateOrderCommand
{
    public int Id { get; set; }
}

🧩 Real-World Architecture in .NET 9

Typical clean architecture uses:

⚠️ Common Mistakes

🎯 When to Use Patterns?

ProblemPattern
Object creation logicFactory
Shared instanceSingleton
Multiple behaviorsStrategy
Loose couplingDI
Data abstractionRepository

🚀 Interview Questions

🏁 Conclusion

Design patterns in .NET 9 are essential for building:

👉 Mastering these patterns will: