Middle
Tell me about the Strategy pattern.
sobes.tech AI
Answer from AI
The 'Strategy' pattern is a behavioral design pattern that allows defining a family of algorithms, encapsulating each one, and making them interchangeable. This enables changing algorithms independently from the clients that use them.
The main idea is to separate algorithms into different classes that implement a common interface, and to choose the appropriate strategy dynamically in the client code.
Example in Java:
// Strategy interface
public interface PaymentStrategy {
void pay(int amount);
}
// Concrete strategies
public class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Payment by credit card: " + amount);
}
}
public class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Payment via PayPal: " + amount);
}
}
// Context using the strategy
public class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
// Usage
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(1000);
cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(2000);
}
}
This approach increases code flexibility and extensibility, making it easier to add new algorithms without modifying existing code.