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);
}
// Concrete strategies
class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Paid $" + amount + " using Credit Card.");
}
}
class PayPalPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Paid $" + amount + " using PayPal.");
}
}
class CashPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Paid $" + amount + " in cash.");
}
}
// 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);
}
}
// 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);
}
}
Output will be :
Paid $25.5 using Credit Card.
Paid $13.75 using PayPal.
Paid $7.0 in cash.
Top comments (0)