You have a family of interchangeable algorithms. The client should be able to pick one at runtime without modifying the calling code.
// ─── EXAMPLE 1 ──────────────────────────────────────────────────────────────
// WHAT WE ARE IMPLEMENTING:
// A check-out cart selecting pricing deductions (flat, percentage, or
// seasonal discounts) at checkout.
//
// WHERE THE STRATEGY FITS IN:
// DiscountStrategy is the Strategy interface. FlatDiscount and
// PercentageDiscount represent Concrete Strategies. CheckoutCart is the
// Context.
// ────────────────────────────────────────────────────────────────────────────
// --- Strategy interface ---
interface PricingStrategy {
double calculatePrice(double basePrice, int hours);
}
// --- Concrete strategies ---
class HourlyPricing implements PricingStrategy {
public double calculatePrice(double basePrice, int hours) {
return basePrice * hours;
}
}
class DailyPricing implements PricingStrategy {
public double calculatePrice(double basePrice, int hours) {
int days = (int) Math.ceil(hours / 24.0);
return basePrice * days * 0.8; // 20% discount
}
}
class WeekendSurchargePricing implements PricingStrategy {
private final double surchargeFactor = 1.5;
public double calculatePrice(double basePrice, int hours) {
return basePrice * hours * surchargeFactor;
}
}
// --- Context (uses strategy) ---
class ParkingFeeCalculator {
private final PricingStrategy strategy;
public ParkingFeeCalculator(PricingStrategy strategy) {
this.strategy = strategy;
}
public double calculate(double basePrice, int hours) {
return strategy.calculatePrice(basePrice, hours);
}
}
public class Main {
public static void main(String[] args) {
// Pick strategy at runtime
ParkingFeeCalculator weekday = new ParkingFeeCalculator(new HourlyPricing());
ParkingFeeCalculator weekend = new ParkingFeeCalculator(new WeekendSurchargePricing());
System.out.println("Weekday 5h: " + weekday.calculate(10, 5)); // 50.0
System.out.println("Weekend 5h: " + weekend.calculate(10, 5)); // 75.0
System.out.println("Daily 30h: " + new ParkingFeeCalculator(new DailyPricing()).calculate(10, 30)); // 240.0
}
}