DEV Community

Cover image for Strategy Pattern
Hicham
Hicham

Posted on

Strategy Pattern

Strategy design pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime

// Strategy interface
interface PaymentStrategy {
    void pay(double amount);
}
Enter fullscreen mode Exit fullscreen mode

// Concrete strategies

class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " using Credit Card.");
    }
}
Enter fullscreen mode Exit fullscreen mode
class PayPalPayment implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " using PayPal.");
    }
}
Enter fullscreen mode Exit fullscreen mode
class CashPayment implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " in cash.");
    }
}
Enter fullscreen mode Exit fullscreen mode

// Context

class Checkout {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void processOrder(double amount) {
        if (paymentStrategy == null) {
            throw new IllegalStateException("Payment strategy not set");
        }
        paymentStrategy.pay(amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

// Client

public class Main {
    public static void main(String[] args) {
        Checkout checkout = new Checkout();

        checkout.setPaymentStrategy(new CreditCardPayment());
        checkout.processOrder(25.50);

        checkout.setPaymentStrategy(new PayPalPayment());
        checkout.processOrder(13.75);

        checkout.setPaymentStrategy(new CashPayment());
        checkout.processOrder(7.00);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output will be :

Paid $25.5 using Credit Card.
Paid $13.75 using PayPal.
Paid $7.0 in cash.

Top comments (0)