interface PaymentStrategy {
    void pay(double amount);
}

class CreditCardPayment implements PaymentStrategy {
    private String name;
    CreditCardPayment(String name) { this.name = name; }

    public void pay(double amount) {
        System.out.println(name
            + " paid $" + amount + " with Credit Card");
    }
}

class PayPalPayment implements PaymentStrategy {
    private String email;
    PayPalPayment(String email) { this.email = email; }

    public void pay(double amount) {
        System.out.println(email
            + " paid $" + amount + " with PayPal");
    }
}

class BitcoinPayment implements PaymentStrategy {
    private String wallet;
    BitcoinPayment(String wallet) { this.wallet = wallet; }

    public void pay(double amount) {
        System.out.println(wallet
            + " paid $" + amount + " with Bitcoin");
    }
}

class ShoppingCart {
    private PaymentStrategy strategy;

    void setPaymentStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    void checkout(double amount) {
        strategy.pay(amount);
    }
}

public static void main(String[] args) {
    ShoppingCart cart = new ShoppingCart();

    cart.setPaymentStrategy(
        new CreditCardPayment("Alice"));
    cart.checkout(100.0);

    cart.setPaymentStrategy(
        new PayPalPayment("alice@example.com"));
    cart.checkout(50.0);
}
Back to Design Patterns
Behavioral Design Pattern

Strategy

The Strategy pattern defines a family of interchangeable algorithms and lets the algorithm vary independently from the clients that use it. Also known as the Policy pattern, it enables selecting an algorithm at runtime by encapsulating each algorithm in a separate class and making them interchangeable through a common interface.