What are design patterns, and how are the Singleton, Adapter, and Strategy patterns typically implemented in C#?
AdvancedDesign patterns are reusable, well-established solutions to recurring software design problems, generally grouped into creational (object creation, like Singleton and Factory Method), structural (relationships between objects, like Adapter and Decorator), and behavioral (object interaction, like Strategy and Observer) categories. Singleton ensures exactly one instance of a class exists application-wide; Adapter lets an existing class with an incompatible interface work where a different interface is expected, without modifying the original class; Strategy lets an algorithm be selected and swapped at runtime by programming against a shared interface rather than hardcoding one specific implementation.
// Singleton
public class Singleton {
private static readonly Singleton _instance = new();
private Singleton() { }
public static Singleton Instance => _instance;
}
// Strategy
public interface IStrategy { void Execute(); }
public class ConcreteStrategyA : IStrategy {
public void Execute() => Console.WriteLine("Executing Strategy A");
}
public class Context {
private readonly IStrategy _strategy;
public Context(IStrategy strategy) => _strategy = strategy;
public void Run() => _strategy.Execute();
}
Real-world example
A payment-processing service uses the Strategy pattern to select between CreditCardStrategy, PayPalStrategy, and BankTransferStrategy implementations of a shared IPaymentStrategy interface at runtime, letting new payment methods be added later without modifying the checkout logic itself.
Design Patterns in Java;OOP