
In many applications, you don’t just create objects — you also need to define how they behave.
And that behavior can change.
Discount calculation, payment processing, sorting logic, validation rules…
Hardcoding all of this quickly turns your code into a jungle of if/else.
That’s where the Strategy pattern comes in.
The Problem: Too Many Conditionals
Let’s say you’re implementing a discount system:
public class DiscountService {
public double applyDiscount(double amount, String type) {
if (type.equals("regular")) {
return amount * 0.9;
} else if (type.equals("premium")) {
return amount * 0.8;
} else if (type.equals("vip")) {
return amount * 0.7;
} else {
return amount;
}
}
}
Problems with this are:
- Every new strategy means modifying this method
- Violates Open/Closed Principle
- Hard to test each variation independently
- Grows into a maintenance nightmare
The Solution: Strategy
Extract each behavior into its own class and make them interchangeable. Strategy implementation example would be:
public interface DiscountStrategy {
double apply(double amount);
}
Then the next step:
public class RegularDiscount implements DiscountStrategy {
public double apply(double amount) {
return amount * 0.9;
}
}
public class PremiumDiscount implements DiscountStrategy {
public double apply(double amount) {
return amount * 0.8;
}
}
public class VipDiscount implements DiscountStrategy {
public double apply(double amount) {
return amount * 0.7;
}
}
The next step:
public class DiscountService {
private final DiscountStrategy strategy;
public DiscountService(DiscountStrategy strategy) {
this.strategy = strategy;
}
public double applyDiscount(double amount) {
return strategy.apply(amount);
}
}
And the Usage of Strategy woul be:
DiscountStrategy strategy = new PremiumDiscount();
DiscountService service = new DiscountService(strategy);
double result = service.applyDiscount(100);
No conditionals. Just behavior injection.
When Should You Use Strategy?
Strategy is perfect when:
- You have multiple ways to perform an operation
- You want to switch behavior at runtime
- You want to avoid if/else or switch blocks
- You need to isolate algorithms
When NOT to Use Strategy
Avoid Strategy when:
- You only have one or two simple variations
- Behavior rarely changes
- You don’t need runtime flexibility

No responses yet