How would you implement the Strategy pattern in Java?

The Strategy pattern implements the Strategy pattern by defining a common interface for a family of algorithms and letting the client swap implementations at runtime. You define a Strategy interface with a single method, write one concrete class per algorithm variant, and have the context class hold a reference to the interface rather than a specific implementation.

Key Points: • Define a Strategy interface with a method such as execute() or apply(). • Create one concrete class per algorithm/behavior, each implementing that interface. • The context (client-facing) class stores a Strategy reference and delegates work to it. • The strategy can be injected via constructor, setter, or passed directly into a method call. • Switching behavior at runtime requires no changes to the context class, only a different strategy instance.

Example: A shipping cost calculator can use a ShippingStrategy interface with StandardShipping and ExpressShipping implementations; the checkout class just calls strategy.calculateCost(order) without knowing which one is active.

Code Example:

interface PaymentStrategy {
    void pay(int amount);
}

class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using Credit Card");
    }
}

class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using PayPal");
    }
}

class Checkout {
    private PaymentStrategy strategy;

    public Checkout(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void process(int amount) {
        strategy.pay(amount);
    }
}

Interview Tip: A concise interview answer is:

"I define a Strategy interface with the method that varies, implement one concrete class per algorithm, and have the client class hold a reference to the interface that can be set at construction or runtime. That way I can swap payment, sorting, or pricing logic without touching the client code."