The Strategy Design Pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one in a separate class, and make them interchangeable. It enables the algorithm to vary independently from the client code that uses it.
Key Components:
- Strategy Interface: Defines a common interface for all supported algorithms.
- Concrete Strategies: Implement different variations of the algorithm defined in the strategy interface.
- Context Class: Maintains a reference to a Strategy object and uses it to execute the algorithm.
Benefits:
- Flexibility: Algorithms can be easily swapped without changing the client code.
- Open/Closed Principle: New algorithms can be added without modifying existing code.
- Encapsulation: Hides the implementation details of the algorithm from the client.
Implementation in Java
Here’s an example of how to implement the Strategy Design Pattern:
1. Define the Strategy Interface
public interface PaymentStrategy {
void pay(int amount);
}
2. Create Concrete Strategies
public 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 ending with " + cardNumber.substring(cardNumber.length() - 4));
}
}
public 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 with email " + email);
}
}
3. Create the Context Class
public class PaymentContext {
private PaymentStrategy strategy;
// Constructor to set the strategy
public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
}
// Setter to change the strategy dynamically
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
// Method to execute the payment
public void pay(int amount) {
strategy.pay(amount);
}
}
4. Use the Pattern
public class Main {
public static void main(String[] args) {
// Using Credit Card payment strategy
PaymentStrategy creditCard = new CreditCardPayment("1234567812345678");
PaymentContext context = new PaymentContext(creditCard);
context.pay(100);
// Switch to PayPal payment strategy
PaymentStrategy payPal = new PayPalPayment("user@example.com");
context.setPaymentStrategy(payPal);
context.pay(200);
}
}
Output:
Paid 100 using Credit Card ending with 5678
Paid 200 using PayPal with email user@example.com
Summary:
The Strategy Design Pattern is useful when you need to define multiple algorithms for a task and allow the client to choose or switch algorithms at runtime. It helps in creating maintainable, reusable, and flexible code.