Strategy Design Pattern
The Strategy pattern is a behavioural design pattern that defines a family of interchangeable algorithms, puts each in its own class, and lets the client choose one at run time.
Instead of long if-else or switch statements, the context object holds a reference to a strategy interface and delegates the work to it. Examples include choosing a payment method, a sorting algorithm or a discount rule without changing the code that uses it.
interface DiscountStrategy { double apply(double amount); }
class FestiveDiscount implements DiscountStrategy {
public double apply(double amount) { return amount * 0.8; }
}
class Checkout {
private DiscountStrategy discount;
Checkout(DiscountStrategy d) { this.discount = d; }
double total(double amount) { return discount.apply(amount); }
}