The Strategy Design Pattern is a behavioral design pattern that enables you to define a family of algorithms, encapsulate each one, and make them interchangeable. It allows the algorithm to be selected at runtime, making your code more flexible and easier to extend.
In this article, we’ll cover:
The Strategy Design Pattern is used to define a set of algorithms and allow the client to choose which algorithm to use at runtime. It separates the algorithm implementation from the client, enabling dynamic selection without modifying the client code.
The Strategy Pattern is ideal when:
Here’s a simple implementation of the Strategy Design Pattern in Java:
Let’s build a payment system where users can choose between different payment methods (Credit Card, PayPal, or Google Pay).
java// Strategy Interface
public interface PaymentStrategy {
void pay(int amount);
}
// Concrete Strategy 1: Credit Card Payment
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
// Concrete Strategy 2: PayPal Payment
public class PayPalPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// Concrete Strategy 3: Google Pay Payment
public class GooglePayPayment implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Google Pay.");
}
}
// Context Class
public class PaymentContext {
private PaymentStrategy paymentStrategy;
// Set the strategy at runtime
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
// Execute the strategy
public void pay(int amount) {
if (paymentStrategy == null) {
throw new IllegalStateException("Payment strategy is not set.");
}
paymentStrategy.pay(amount);
}
}
// Client Code
public class Client {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
// Pay using Credit Card
context.setPaymentStrategy(new CreditCardPayment());
context.pay(100);
// Pay using PayPal
context.setPaymentStrategy(new PayPalPayment());
context.pay(200);
// Pay using Google Pay
context.setPaymentStrategy(new GooglePayPayment());
context.pay(300);
}
}
Here’s the UML diagram representing the Strategy Pattern for the Payment System:
On Coudo AI, you can:
The Strategy Design Pattern is a powerful tool for creating flexible and extensible systems. By encapsulating algorithms and making them interchangeable, this pattern allows for dynamic behavior selection and cleaner code. Start practicing the Strategy Pattern on Coudo AI and master this essential design pattern.