Provide an example where the Strategy pattern simplifies the management of multiple algorithms.

A common example of the Strategy pattern simplifying algorithm management is a payment processing system that needs to support multiple payment methods, each with its own processing logic, without cluttering the checkout code with conditionals.

Key Points: • A PaymentStrategy interface declares a method like pay(amount). • Each payment method — CreditCardStrategy, PayPalStrategy, CryptoStrategy — implements the interface with its own logic. • The checkout class holds a PaymentStrategy reference and calls pay() without knowing which method is active. • The strategy is selected at runtime, often based on user input or configuration, and injected into the checkout class. • Adding a new payment method means adding a new class, not modifying existing checkout logic or conditionals.

Example: Instead of a checkout method with a long if (type.equals("CREDIT_CARD")) ... else if (type.equals("PAYPAL")) ... chain, the client just calls strategy.pay(amount) where strategy was selected once based on the user's chosen method.

Code Example:

interface PaymentStrategy {
    void pay(double amount);
}

class PayPalStrategy implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid " + amount + " via PayPal");
    }
}

class Checkout {
    private PaymentStrategy strategy;
    Checkout(PaymentStrategy strategy) { this.strategy = strategy; }
    void checkout(double amount) { strategy.pay(amount); }
}

Interview Tip: A concise interview answer is:

"A payment system is a great example — instead of a big conditional picking logic based on payment type, I define a PaymentStrategy interface with one implementation per method and let the checkout class just call strategy.pay(amount). Adding a new payment method later is just a new class, with zero changes to the checkout logic."