Sobes.tech
Middle

What is the purpose of the 'Strategy' design pattern?

sobes.tech AI

Answer from AI

The "Strategy" pattern is used for:

  1. Defining a family of algorithms: Each algorithm is encapsulated in a separate class that implements a common interface.
  2. Interchangeability of algorithms: Client code can easily switch between different algorithms at runtime using polymorphism, without modifying the client class.
  3. Eliminating conditional logic: Replaces multiple if/else or switch statements based on the algorithm type.
  4. Isolation of algorithms: Allows changing or adding new algorithms independently of the client using them.

Example structure:

// Common interface for strategies
interface PaymentStrategy {
    void pay(int amount);
}

// Concrete strategy: credit card payment
class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        // Credit card payment logic
        System.out.println("Paid " + amount + " using a credit card.");
    }
}

// Concrete strategy: PayPal payment
class PaypalPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        // PayPal payment logic
        System.out.println("Paid " + amount + " using PayPal.");
    }
}

// Context using the strategy
class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int totalAmount) {
        // Using the strategy for payment
        paymentStrategy.pay(totalAmount);
    }
}

// Usage example
// public class Main {
//     public static void main(String[] args) {
//         ShoppingCart cart = new ShoppingCart();

//         // Using credit card payment strategy
//         cart.setPaymentStrategy(new CreditCardPayment());
//         cart.checkout(100);

//         // Switching to PayPal payment strategy
//         cart.setPaymentStrategy(new PaypalPayment());
//         cart.checkout(200);
//     }
// }