在Java中实现基于策略的决策模式

原创 阳光穿透心脏的1/2处 2024-09-19 16:00 117阅读 0赞

在Java中实现基于策略的决策模式,可以使用《设计模式:解决常见问题》(Gang of Four)中的策略模式进行实现。下面是一个简单的例子:

  1. 创建策略接口(Strategy Interface):
  1. // 策略接口
  2. public interface PaymentStrategy {
  3. // 计算付款金额
  4. double calculatePayment(double purchasePrice);
  5. }
  1. 创建具体策略类(Concrete Strategy Classes):
  1. // 第一种支付策略:信用卡支付
  2. public class CreditCardPaymentStrategy implements PaymentStrategy {
  3. @Override
  4. public double calculatePayment(double purchasePrice) {
  5. // 假设信用卡手续费为购买价格的1%
  6. return purchasePrice + (purchasePrice * 0.01));
  7. }
  8. }
  9. // 第二种支付策略:现金支付
  10. public class CashPaymentStrategy implements PaymentStrategy {
  11. @Override
  12. public double calculatePayment(double purchasePrice) {
  13. // 现金支付无需手续费
  14. return purchasePrice;
  15. }
  16. }
  1. 创建上下文(Context)类:
  1. // 上下文类,用于存储和调用支付策略
  2. public class PaymentContext {
  3. private PaymentStrategy paymentStrategy;
  4. public PaymentContext(PaymentStrategy paymentStrategy) {
  5. this.paymentStrategy = paymentStrategy;
  6. }
  7. public double calculatePayment(double purchasePrice) {
  8. return paymentStrategy.calculatePayment(purchasePrice);
  9. }
  10. }
  1. 在主程序中使用上下文来决定支付策略:
  1. public class Main {
  2. public static void main(String[] args) {
  3. // 创建两种支付策略
  4. PaymentStrategy creditCardPayment = new CreditCardPaymentStrategy();
  5. PaymentStrategy cashPayment = new CashPaymentStrategy();
  6. // 创建上下文,选择一种支付策略
  7. PaymentContext paymentContext = new PaymentContext(creditCardPayment);
  8. // 假设购买价格为100元
  9. double purchasePrice = 100;
  10. // 计算并打印付款金额
  11. double paymentAmount = paymentContext.calculatePayment(purchasePrice);
  12. System.out.println("付款金额: " + paymentAmount);
  13. }
  14. }

这样,你就可以根据实际需求选择不同的支付策略了。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读