在Java中实现基于策略的决策模式
在Java中实现基于策略的决策模式,可以使用《设计模式:解决常见问题》(Gang of Four)中的策略模式进行实现。下面是一个简单的例子:
- 创建策略接口(Strategy Interface):
// 策略接口
public interface PaymentStrategy {
// 计算付款金额
double calculatePayment(double purchasePrice);
}
- 创建具体策略类(Concrete Strategy Classes):
// 第一种支付策略:信用卡支付
public class CreditCardPaymentStrategy implements PaymentStrategy {
@Override
public double calculatePayment(double purchasePrice) {
// 假设信用卡手续费为购买价格的1%
return purchasePrice + (purchasePrice * 0.01));
}
}
// 第二种支付策略:现金支付
public class CashPaymentStrategy implements PaymentStrategy {
@Override
public double calculatePayment(double purchasePrice) {
// 现金支付无需手续费
return purchasePrice;
}
}
- 创建上下文(Context)类:
// 上下文类,用于存储和调用支付策略
public class PaymentContext {
private PaymentStrategy paymentStrategy;
public PaymentContext(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public double calculatePayment(double purchasePrice) {
return paymentStrategy.calculatePayment(purchasePrice);
}
}
- 在主程序中使用上下文来决定支付策略:
public class Main {
public static void main(String[] args) {
// 创建两种支付策略
PaymentStrategy creditCardPayment = new CreditCardPaymentStrategy();
PaymentStrategy cashPayment = new CashPaymentStrategy();
// 创建上下文,选择一种支付策略
PaymentContext paymentContext = new PaymentContext(creditCardPayment);
// 假设购买价格为100元
double purchasePrice = 100;
// 计算并打印付款金额
double paymentAmount = paymentContext.calculatePayment(purchasePrice);
System.out.println("付款金额: " + paymentAmount);
}
}
这样,你就可以根据实际需求选择不同的支付策略了。
还没有评论,来说两句吧...