Strategy Design Pattern in Java
Strategy keeps several ways (algorithms) to do one job in separate classes. You can switch between them while the program runs.
Real life example
Going to the office by car, bus or bike. The goal is same, the way is different.
When to use
You have many ways to do the same task, like payment methods, sorting or discounts.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
cart.setPayment(new UpiPayment());
cart.checkout(500); // Paid 500 by UPI
cart.setPayment(new CardPayment());
cart.checkout(800); // Paid 800 by Card
}
}
interface Payment { void pay(int amount); }
class UpiPayment implements Payment { public void pay(int a) { System.out.println("Paid " + a + " by UPI"); } }
class CardPayment implements Payment { public void pay(int a) { System.out.println("Paid " + a + " by Card"); } }
class Cart {
private Payment payment;
void setPayment(Payment p) { payment = p; } // choose the strategy
void checkout(int amount) { payment.pay(amount); }
}Output
Paid 500 by UPI
Paid 800 by Card