Video in progress

What is the Strategy pattern? Explain it with payment methods.

Strategy puts several ways of doing one job into separate classes and swaps them through a common interface. The main code doesn't know which way was chosen, it just calls the interface.

📖 Answer

Say a shop takes payment by card, Click or cash. Without Strategy the checkout method turns into a long if-else, and every time a new method is added, that method changes.

public interface PaymentMethod {
    PaymentResult pay(BigDecimal amount);
}

class CardPayment implements PaymentMethod {
    public PaymentResult pay(BigDecimal amount) { /* bank API */ return PaymentResult.ok(); }
}

class CashOnDelivery implements PaymentMethod {
    public PaymentResult pay(BigDecimal amount) { return PaymentResult.pending(); }
}

class Checkout {
    PaymentResult finish(Cart cart, PaymentMethod method) {
        return method.pay(cart.total()); // which method doesn't matter
    }
}

Now a new payment method is just a new class, and Checkout isn't touched. Testing each strategy separately is easy too.

The most familiar Strategy in the JDK is Comparator: list.sort(byPrice) and list.sort(byName): the sorting is the same, the rule is different.