Sobes.tech
Middle

What do you know 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 the behavior of an object at runtime without altering its class.

Main idea:

  • Create a strategy interface with a defined method.
  • Several classes implement this interface, providing different algorithm options.
  • The context contains a reference to a strategy object and delegates the task execution to it.

Example of usage: in an ERP system, different methods of calculating discounts for clients — each method implemented as a separate strategy.

interface DiscountStrategy {
    double applyDiscount(double price);
}

class NoDiscount implements DiscountStrategy {
    public double applyDiscount(double price) {
        return price;
    }
}

class SeasonalDiscount implements DiscountStrategy {
    public double applyDiscount(double price) {
        return price * 0.9;
    }
}

class Customer {
    private DiscountStrategy discountStrategy;

    public Customer(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public double getPrice(double price) {
        return discountStrategy.applyDiscount(price);
    }
}

This approach simplifies code extension and maintenance.