The Strategy Pattern is a way to keep different behaviours separate instead of putting everything inside one big if/else block.
In simple words:
Strategy Pattern means choosing the right way to do something at runtime.
Layman Example
Imagine you want to travel to office.
You have different options:
- Walk
- Take a bus
- Drive a car
- Take a train
The goal is the same: reach the office.
But the method, or strategy, is different.
Software Example
Suppose an application needs to calculate delivery charges.
- Standard delivery has one rule
- Express delivery has another rule
- Free delivery has another rule
Without Strategy Pattern, we may write everything in one method using many conditions.
if (deliveryType == "Standard")
{
// standard delivery logic
}
else if (deliveryType == "Express")
{
// express delivery logic
}
else if (deliveryType == "Free")
{
// free delivery logic
}
This works, but as the rules grow, the code becomes harder to read and maintain.
How Strategy Pattern Helps
With Strategy Pattern, each rule is moved into its own class.
StandardDeliveryStrategyExpressDeliveryStrategyFreeDeliveryStrategy
Each class handles only one behaviour.
The main code simply chooses the correct strategy and uses it.
Implementation Example
First, create a common interface for all delivery charge strategies.
public interface IDeliveryChargeStrategy
{
decimal Calculate();
}
Now create separate classes for each strategy.
public class StandardDeliveryStrategy : IDeliveryChargeStrategy
{
public decimal Calculate()
{
return 5;
}
}
public class ExpressDeliveryStrategy : IDeliveryChargeStrategy
{
public decimal Calculate()
{
return 15;
}
}
public class FreeDeliveryStrategy : IDeliveryChargeStrategy
{
public decimal Calculate()
{
return 0;
}
}
Now choose the correct strategy based on the delivery type.
public class DeliveryChargeCalculator
{
public decimal Calculate(string deliveryType)
{
IDeliveryChargeStrategy strategy = deliveryType switch
{
"Standard" => new StandardDeliveryStrategy(),
"Express" => new ExpressDeliveryStrategy(),
"Free" => new FreeDeliveryStrategy(),
_ => throw new ArgumentException("Invalid delivery type")
};
return strategy.Calculate();
}
}
Usage:
var calculator = new DeliveryChargeCalculator();
var charge = calculator.Calculate("Express");
Console.WriteLine(charge); // 15
Why Use It?
- Code becomes cleaner
- Large
if/elseblocks are reduced - Each behaviour is easier to change
- Each rule can be tested separately
- New behaviours can be added without disturbing old ones
When to Use It?
Use Strategy Pattern when the same action can be done in different ways.
Common examples:
- Payment methods
- Discount calculation
- Delivery charge calculation
- File export formats
- Notification sending
- Data update rules
In a Nutshell
The Strategy Pattern helps us separate different ways of doing the same thing.
Instead of writing one large method with many conditions, we create separate classes for each behaviour and choose the right one when needed.