Strategy - rFronteddu/general_wiki GitHub Wiki

The Strategy Design Pattern is used to define a family of algorithms, encapsulate each one, and make them interchangeable. This allows the algorithm to vary independently from clients that use it.

Suppose we have a Payment system that can support different payment methods like CreditCardPayment and PayPalPayment. We can use the Strategy Design Pattern to achieve this.

Step-by-Step Implementation:

  • Strategy Interface: Define a common interface for all supported algorithms.
  • Concrete Strategies: Implement the algorithms following the strategy interface.
  • Context Class: Use a strategy object to perform the algorithm.

Explanation:

  • PaymentStrategy: The strategy interface with a pay method.
  • CreditCardPayment and PayPalPayment: Concrete strategies that implement the PaymentStrategy interface.
  • ShoppingCart: The context class that holds the items and a reference to a PaymentStrategy to perform the payment.

In this way, the payment method can be changed at runtime without altering the ShoppingCart class, demonstrating the flexibility and reusability provided by the Strategy Design Pattern.

Code Example

// Strategy interface
public interface PaymentStrategy {
    void pay(int amount);
}
// Concrete Strategy for Credit Card Payment
public class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;
    private String name;
    private String cvv;
    private String dateOfExpiry;
    
    public CreditCardPayment(String cardNumber, String name, String cvv, String dateOfExpiry) 
    {
        this.cardNumber = cardNumber;
        this.name = name;
        this.cvv = cvv;
        this.dateOfExpiry = dateOfExpiry;
    }
    
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using Credit Card.");
    }
}

// Concrete Strategy for PayPal Payment
public class PayPalPayment implements PaymentStrategy {
    private String emailId;
    private String password;
    
    public PayPalPayment(String emailId, String password) {
        this.emailId = emailId;
        this.password = password;
    }
    
    @Override
    public void pay(int amount) {
        System.out.println("Paid " + amount + " using PayPal.");
    }
}
// Context class
public class ShoppingCart {
    private List<Item> items;
    private PaymentStrategy paymentStrategy;
    
    public ShoppingCart() {
        this.items = new ArrayList<>();
    }
    
    public void addItem(Item item) {
        items.add(item);
    }
    
    public void removeItem(Item item) {
        items.remove(item);
    }
    
    public int calculateTotal() {
        int sum = 0;
        for (Item item : items) {
            sum += item.getPrice();
        }
        return sum;
    }
    
    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }
    
    public void checkout() {
        int amount = calculateTotal();
        paymentStrategy.pay(amount);
    }
}

Usage

public class StrategyPatternExample {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        
        Item item1 = new Item("1234", 100);
        Item item2 = new Item("5678", 200);
        
        cart.addItem(item1);
        cart.addItem(item2);
        
        // Pay with credit card
        cart.setPaymentStrategy(new CreditCardPayment("1234567890123456", "John Doe", "123", "12/23"));
        cart.checkout();
        
        // Pay with PayPal
        cart.setPaymentStrategy(new PayPalPayment("[email protected]", "password"));
        cart.checkout();
    }
}
⚠️ **GitHub.com Fallback** ⚠️