What is Strategy Pattern?
The Strategy Pattern is a behavioral design pattern that allows you to change the behavior of a class at runtime without modifying its code.
Instead of hardcoding logic (like tax calculation), you define multiple strategies and inject the required one dynamically.
Why Use Strategy Pattern?
- Avoid multiple
if-elseorswitchconditions - Make logic easily replaceable
- Follow Open/Closed Principle (open for extension, closed for modification)
- Improve maintainability
Real-Time Scenario
In an Invoice Management System, tax calculation can vary:
- GST (India)
- No Tax
- Future: VAT, Service Tax, etc.
Instead of modifying the same method every time, we plug different strategies.
Implementation
Step 1: Create Strategy Interface
public interface ITaxStrategy
{
decimal Calculate(decimal amount);
}
Step 2: Implement Concrete Strategies
public class GstTax : ITaxStrategy
{
public decimal Calculate(decimal amount) => amount * 0.18m;
}
public class NoTax : ITaxStrategy
{
public decimal Calculate(decimal amount) => 0;
}
Step 3: Use Strategy in Service
public class InvoiceService
{
private readonly ITaxStrategy _tax;
public InvoiceService(ITaxStrategy tax)
{
_tax = tax;
}
public decimal GetTotal(decimal amount)
{
return amount + _tax.Calculate(amount);
}
}
Usage Example
var invoiceService = new InvoiceService(new GstTax());
var total = invoiceService.GetTotal(1000);
Console.WriteLine(total); // 1180
Key Concept
Instead of:
if(type == "GST") { ... }
else if(type == "NoTax") { ... }
We do:
InvoiceService(new GstTax());
👉 Behavior changes without touching existing code
Advantages
- Clean and maintainable code
- Easy to add new tax rules
- No modification of existing logic
- Better testability
Disadvantages
- Increases number of classes
- Slightly more setup required
- Overkill for simple logic
When to Use
- Multiple algorithms for same task
- Logic changes frequently
- Want to avoid conditional complexity
- Need runtime flexibility
Real Project Mapping (.NET + Angular)
- Backend: Tax strategy injected via Dependency Injection
- Frontend: User selects tax type (dropdown)
- API: Pass selected strategy → calculate dynamically
Pro Tip (Advanced .NET Usage)
Register strategies in DI:
builder.Services.AddScoped<ITaxStrategy, GstTax>();
Or use Factory + Strategy together for dynamic selection.
Summary
The Strategy Pattern helps you:
- Replace complex conditions
- Switch behavior at runtime
- Build scalable business logic
👉 Perfect for real-world apps like Invoice, Payment, Pricing engines
Comments
Post a Comment