Overview
The Strategy Design Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows the algorithm to vary independently from clients that use it.
Key Characteristics
- Encapsulates a family of algorithms, making them interchangeable.
- Promotes the Open/Closed Principle by allowing new algorithms to be added without modifying existing code.
- Delegates the decision of which algorithm to use to the client or context.
Implementation
The following is an example of a Strategy implementation in Java:
// Strategy interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card: " + cardNumber);
}
}
class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) {
this.email = email;
}
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal: " + email);
}
}
// Context
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
if (paymentStrategy == null) {
throw new IllegalStateException("Payment strategy is not set.");
}
paymentStrategy.pay(amount);
}
}
// Demo
public class StrategyDemo {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
// Pay with Credit Card
cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
cart.checkout(100);
// Pay with PayPal
cart.setPaymentStrategy(new PayPalPayment("[email protected]"));
cart.checkout(200);
}
}
When to Use
- When you have multiple algorithms or behaviors that can be applied interchangeably.
- When you want to avoid using conditional statements to choose between different behaviors.
Advantages
- Promotes code reusability by encapsulating algorithms.
- Adheres to the Open/Closed Principle by making it easy to add new strategies.
Disadvantages
- Can increase the number of classes in the codebase.
- The client must be aware of the different strategies to select an appropriate one.