designpatterns/behavioral

you separate how something is done from who is using it.

The strategy pattern is a behavioral design pattern that:

  • Defines a family of algorithms (Strategies)
  • Encapsulates each one into a separate class.
  • Let’s you swap strategies at runtime without changing the code that uses them.

Imagine that you have to get to the airport. You can catch a bus, order a cab, or get on your bicycle. These are your transportation strategies. You can pick one of the strategies depending on factors such as budget or time constraints.

Real World Example

  • Sorting algorithms (quicksort, mergesort, bubblesort).
  • Payment methods (credit, debit, PayPal, crypto).
  • Compression formats (ZIP, RAR, TAR).
  • Character movement strategies in games (aggressive, defensive, evasive).
  • Navigation route planning (fastest, shortest, scenic).

Example

🌟 Strategy in Java / Design Patterns

// Strategy interface
interface PaymentStrategy {
    void pay(double amount);
}
 
// Concrete strategies
class CreditCardPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " using Credit Card.");
    }
}
 
class PayPalPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " using PayPal.");
    }
}
 
class CryptoPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " using Cryptocurrency.");
    }
}
 
// Context
class ShoppingCart {
    private PaymentStrategy paymentStrategy;
 
    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.paymentStrategy = strategy;
    }
 
    public void checkout(double amount) {
        if (paymentStrategy == null) {
            System.out.println("No payment method selected!");
        } else {
            paymentStrategy.pay(amount);
        }
    }
}
 
// Main app
public class PaymentApp {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
 
        // Pay with Credit Card
        cart.setPaymentStrategy(new CreditCardPayment());
        cart.checkout(100.0);
 
        // Pay with PayPal
        cart.setPaymentStrategy(new PayPalPayment());
        cart.checkout(50.0);
 
        // Pay with Crypto
        cart.setPaymentStrategy(new CryptoPayment());
        cart.checkout(200.0);
    }
}