Junior — Middle
Can you explain what the strategy pattern is and how to apply it in software development?
sobes.tech AI
Answer from AI
The Strategy pattern is a behavioral design pattern that enables defining a family of algorithms, encapsulating each one, and making them interchangeable. It helps change the behavior of an object at runtime without modifying its code.
Application:
- Create a strategy interface with a method describing the algorithm.
- Implement several classes that implement this interface with different algorithms.
- In the context class, store a reference to a strategy object and invoke the algorithm method through it.
Example in Java:
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paying " + amount + " with a credit card");
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paying " + amount + " via PayPal");
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
// Usage:
ShoppingCart cart = new ShoppingCart();
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(1000);
cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(500);
This approach simplifies the extension and maintenance of the code, allowing new algorithms to be added without changing existing code.