Strategy Pattern in C# – Real-Time Example (Dynamic Behavior Switching)

What is Strategy Pattern?

The Strategy Pattern is a behavioral design pattern that allows you to change an object's behavior at runtime by selecting different algorithms or strategies dynamically.

Instead of using large:


if-else
switch

We encapsulate behaviors into separate classes.


Why Use Strategy Pattern?

  • Remove complex if-else conditions
  • Change behavior dynamically
  • Follow Open/Closed Principle
  • Improve maintainability and scalability

Real-Time Scenario

Invoice System:

  • GST Tax
  • No Tax
  • International Tax

👉 Tax calculation changes dynamically based on customer type/location.


Real-Time Example – Invoice Tax Calculation


Step 1: Strategy Interface


public interface ITaxStrategy
{
    decimal Calculate(decimal amount);
}


Step 2: Concrete Strategies

GST Tax


public class GstTax : ITaxStrategy
{
    public decimal Calculate(decimal amount)
    {
        return amount * 0.18m;
    }
}


No Tax


public class NoTax : ITaxStrategy
{
    public decimal Calculate(decimal amount)
    {
        return 0;
    }
}


International Tax


public class InternationalTax : ITaxStrategy
{
    public decimal Calculate(decimal amount)
    {
        return amount * 0.25m;
    }
}


Step 3: Context Class


public class InvoiceService
{
    private readonly ITaxStrategy _taxStrategy;

    public InvoiceService(ITaxStrategy taxStrategy)
    {
        _taxStrategy = taxStrategy;
    }

    public decimal GetTotal(decimal amount)
    {
        return amount + _taxStrategy.Calculate(amount);
    }
}


Usage Example


ITaxStrategy strategy = new GstTax();

var invoice = new InvoiceService(strategy);

Console.WriteLine(invoice.GetTotal(1000));


Output


1180


Dynamic Behavior Change


var invoice1 =
    new InvoiceService(new GstTax());

var invoice2 =
    new InvoiceService(new NoTax());

var invoice3 =
    new InvoiceService(new InternationalTax());

👉 Behavior changes without modifying existing code.


Key Concept

Instead of:


if(country == "India")
{
    // GST
}
else if(country == "Export")
{
    // International tax
}

We do:


ITaxStrategy strategy

👉 Cleaner and scalable design.


Diagram Understanding


Client
   ↓
InvoiceService
   ↓
ITaxStrategy
   ↓
----------------------
GstTax
NoTax
InternationalTax

👉 Strategy chosen dynamically.


Advantages

  • ✔ Removes if-else complexity
  • ✔ Easy to extend
  • ✔ Runtime behavior switching
  • ✔ Better maintainability
  • ✔ Follows SOLID principles

Disadvantages

  • ✖ More classes/interfaces
  • ✖ Slight complexity increase
  • ✖ Client must know available strategies

When to Use

Use Strategy Pattern when:

  • Multiple algorithms exist
  • Behavior changes dynamically
  • Large if-else blocks appear
  • Business rules change frequently

Real Project Mapping (.NET + Angular)

Feature Usage
Tax calculation Strategy
Payment methods Strategy
Discount engines Strategy
File export formats Strategy
Authentication providers Strategy

ASP.NET Core Real Example

Authentication providers:

  • JWT Authentication
  • Google Authentication
  • OAuth Authentication

👉 Different authentication strategies.


Advanced Example – Payment System


IPaymentStrategy
 ├── UpiPayment
 ├── CardPayment
 └── NetBankingPayment

👉 Payment method selected dynamically.


Strategy vs Factory

Strategy Factory
Focus on behavior Focus on object creation
Runtime algorithm switching Object instantiation
Encapsulates logic Encapsulates creation

Pro Tip

Strategy Pattern works well with:

  • Factory Pattern
  • Dependency Injection
  • Configuration-driven systems
  • Rule engines

Summary

Strategy Pattern helps you:

  • Change behavior dynamically
  • Remove complex conditions
  • Build scalable business logic

👉 Perfect for:

  • Tax systems
  • Payment gateways
  • Pricing engines
  • Authentication providers

Comments

Popular posts from this blog

Promises in Angular

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Csharp Coding - Session