Skip to main content

Posts

Showing posts with the label strategy

Dependency Injection In .NET Core With Strategy Pattern

In the previous post, we gave an introduction and explained the basic concept of the  Strategy Pattern . Now, we want to go a bit further and demonstrate how it works in practice alongside a dependency injection in .NET Core. Instead of manually instantiating strategies, we let the ASP.NET Core DI container inject the correct implementation at runtime. Example For the showing purposes, let us asume that we are implementing some payment service, and we want to use one service at the time, depending on user input. For our strategy pattern, we would need following components: Interface public interface IPaymentStrategy { void Pay ( decimal amount ) ; } Concrete Strategies public class CreditCardPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amount} using Credit Card."); } } public class PayPalPayment : IPaymentStrategy { public void Pay(decimal amount) { Console.WriteLine($"Paid ${amoun...

Design Patterns: Strategy

The Strategy Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows the algorithm to be selected at runtime, providing flexibility in designing software. It’s particularly useful when you have multiple ways of performing a task, and you want to choose the implementation dynamically without altering the client code. When To Use It? You Have Multiple Algorithms or Behaviors. Use it when you have a need for muplitple ways of performing a task, and you want to make these implementations interchangeable. Examples: Different sorting algorithms, payment methods, discount calculations... You Want to Eliminate Conditional Logic.  If you find yourself writing large if-else or switch statements to decide which algorithm to use, this pattern can simplify and clean up your code. Examples: A game character with different attack styles  You Need Runtime Flexibility.  Use this pattern if the ...