策略设计模式是一种行为模式,其中我们有多种算法/策略来实现任务,以及使用哪种算法/策略供客户选择。 各种算法选项封装在各个类中。
在本教程中,我们将学习如何在Java中实现策略设计模式。
让我们首先看一下策略设计模式的UML表示:
在这里,我们有:
众所周知,任何购物网站都提供多种付款方式。 所以,让我们用这个例子来实现策略模式。
我们首先定义PaymentStrategy接口:
public interface PaymentStrategy {
void pay(Shopper shopper);
}
现在,让我们定义两种最常见的支付方式,即货到付款和卡支付,作为两个具体的策略类:
public class CashOnDeliveryStrategy implements PaymentStrategy {
@Override
public void pay(Shopper shopper) {
double amount = shopper.getShoppingCart().getTotal();
System.out.println(shopper.getName() + " selected Cash On Delivery for Rs." + amount );
}
}
public class CardPaymentStrategy implements PaymentStrategy {
@Override
public void pay(Shopper shopper) {
CardDetails cardDetails = shopper.getCardDetails();
double amount = shopper.getShoppingCart().getTotal();
completePayment(cardDetails, amount);
System.out.println("Credit/Debit card Payment of Rs. " + amount + " made by " + shopper.getName());
}
private void completePayment(CardDetails cardDetails, double amount) { ... }
}
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStratgey strategy) {
this.strategy = strategy;
}
public void makePayment(Shopper shopper) {
this.strategy.pay(shopper);
}
}
此外,我们的Shopper类看起来类似于:
public class Shopper {
private String name;
private CardDetails cardDetails;
private ShoppingCart shoppingCart;
//suitable constructor , getters and setters
public void addItemToCart(Item item) {
this.shoppingCart.add(item);
}
public void payUsingCOD() {
PaymentContext pymtContext = new PaymentContext(new CashOnDeliveryStrategy());
pymtContext.makePayment(this);
}
public void payUsingCard() {
PaymentContext pymtContext = new PaymentContext(new CardPaymentStrategy());
pymtContext.makePayment(this);
}
}
我们系统中的购物者可以使用其中一种可用的购买策略进行支付。 对于我们的示例,我们的PaymentContext类接受所选的付款策略,然后为该策略调用pay()方法。
https://www.leftso.com/article/676.html