Junior — Middle
Could you tell about your experience implementing the strategy pattern in projects?
sobes.tech AI
Answer from AI
I used the strategy pattern to implement flexible discount calculation logic in an online store. Instead of hard-coded conditions, each discount strategy was encapsulated in a separate class implementing a common interface. This allowed easy addition of new discount types without modifying existing code.
Example in Java:
interface DiscountStrategy {
double applyDiscount(double price);
}
class NoDiscount implements DiscountStrategy {
public double applyDiscount(double price) {
return price;
}
}
class PercentageDiscount implements DiscountStrategy {
private double percent;
public PercentageDiscount(double percent) {
this.percent = percent;
}
public double applyDiscount(double price) {
return price * (1 - percent / 100);
}
}
class ShoppingCart {
private DiscountStrategy discountStrategy;
public ShoppingCart(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public double calculatePrice(double price) {
return discountStrategy.applyDiscount(price);
}
}
This approach improved the extensibility and testability of the code.