The Strategy pattern addresses the need to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. It is useful when you have multiple ways to perform a specific task and want to choose the algorithm at runtime.
The Strategy pattern involves three main components:
The context delegates the execution of the algorithm to the strategy object, which allows the algorithm to be selected at runtime.
A practical example of the Strategy pattern is in a payment processing system where different payment methods (e.g., credit card, PayPal, bank transfer) are implemented as different strategies. The client can choose the appropriate payment strategy at runtime.
Strategy pattern in code:
java // Strategy Interface public interface PaymentStrategy { void pay(int amount); } // Concrete Strategy 1 public class CreditCardPayment implements PaymentStrategy { private String cardNumber; public CreditCardPayment(String cardNumber) { this.cardNumber = cardNumber; } @Override public void pay(int amount) { System.out.println(amount + " paid with credit card " + cardNumber); } } // Concrete Strategy 2 public class PayPalPayment implements PaymentStrategy { private String email; public PayPalPayment(String email) { this.email = email; } @Override public void pay(int amount) { System.out.println(amount + " paid using PayPal account " + email); } } // Context public class ShoppingCart { private PaymentStrategy paymentStrategy; public void setPaymentStrategy(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } public void checkout(int amount) { paymentStrategy.pay(amount); } } // Client code public class Client { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9876-5432")); cart.checkout(100); cart.setPaymentStrategy(new PayPalPayment("user@example.com")); cart.checkout(200); } }
The above is the detailed content of Understanding the Strategy Design Pattern in Java. For more information, please follow other related articles on the PHP Chinese website!