The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one of them, and make them interchangeable. The strategy pattern lets the algorithm vary independently from clients that use it.
Here's an example of the Strategy pattern implemented in Java:
// Strategy interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete strategies
class CreditCardPaymentStrategy implements PaymentStrategy {
private String cardNumber;
private String expirationDate;
private String cvv;
public CreditCardPaymentStrategy(String cardNumber, String expirationDate, String cvv) {
this.cardNumber = cardNumber;
this.expirationDate = expirationDate;
this.cvv = cvv;
}
@Override
public void pay(int amount) {
// Logic for making payment via credit card
System.out.println("Paid " + amount + " via Credit Card");
}
}
class PayPalPaymentStrategy implements PaymentStrategy {
private String email;
private String password;
public PayPalPaymentStrategy(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public void pay(int amount) {
// Logic for making payment via PayPal
System.out.println("Paid " + amount + " via PayPal");
}
}
// Context class
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 StrategyExample {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
// Pay with credit card
cart.setPaymentStrategy(new CreditCardPaymentStrategy("1234 5678 9012 3456", "12/25", "123"));
cart.checkout(100);
// Pay with PayPal
cart.setPaymentStrategy(new PayPalPaymentStrategy("example@example.com", "password123"));
cart.checkout(50);
}
}
In this example:
PaymentStrategyis the strategy interface defining the method for making a payment.CreditCardPaymentStrategyandPayPalPaymentStrategyare concrete implementations of thePaymentStrategyinterface, each encapsulating the algorithm for making payments via credit card and PayPal, respectively.ShoppingCartacts as the context class, which holds a reference to the current payment strategy and delegates the payment to the selected strategy.- In the client code, we create a shopping cart object and set different payment strategies based on the user's choice.
If this article is helpful to you, please consider making a donation to allow an older programmer to live with more dignity. Scan the QR code to pay 1 cent. thanks very much my friend

策略模式是一种行为设计模式,它使你能在运行时定义一系列算法,并将每种算法封装起来,使其互换使用。该模式让算法独立于使用它的客户。

1587

被折叠的 条评论
为什么被折叠?



