本文共 3485 字,大约阅读时间需要 11 分钟。
在商场促销场景下,使用策略模式可以有效地实现计算最终支付金额的功能。本文将详细介绍相关实现。
package com.zawl.designpattern.strategy;public interface CashSuper { BigDecimal acceptCash(BigDecimal money);} 该接口定义了一个通用收费处理方法,用于计算最终支付金额。
package com.zawl.designpattern.strategy;public class CashNormal implements CashSuper { @Override public BigDecimal acceptCash(BigDecimal money) { return money; }} 实现了接口中的acceptCash方法,直接返回输入金额,不做任何调整。
package com.zawl.designpattern.strategy;public class CashDiscount implements CashSuper { private BigDecimal discountRate = new BigDecimal(1); public CashDiscount(BigDecimal discountRate) { this.discountRate = discountRate; } @Override public BigDecimal acceptCash(BigDecimal money) { return money.multiply(discountRate).setScale(2, BigDecimal.ROUND_HALF_UP); }} 支持打折收费,根据输入的折扣率计算最终金额。
package com.zawl.designpattern.strategy;public class CashReturn implements CashSuper { private BigDecimal moneyCondition = BigDecimal.ZERO; private BigDecimal moneyReturn = BigDecimal.ZERO; public CashReturn(double moneyCondition, double moneyReturn) { this.moneyCondition = new BigDecimal(moneyCondition); this.moneyReturn = new BigDecimal(moneyReturn); } @Override public BigDecimal acceptCash(BigDecimal money) { if (money.compareTo(moneyCondition) >= 0) { money = money.subtract(moneyReturn); } return money; }} 支持返现收费,根据消费金额和满足返现条件计算最终金额。
package com.zawl.designpattern.strategy;public class CashContext { private CashSuper cashSuper; public CashContext(String type) { switch (type) { case CashConstants.NORMAL: cashSuper = new CashNormal(); break; case CashConstants.DISCOUNT: cashSuper = new CashDiscount(new BigDecimal(0.8)); break; case CashConstants.RETURN: cashSuper = new CashReturn(300, 100); break; } } public BigDecimal getResult(double money) { return cashSuper.acceptCash(new BigDecimal(money)); } enum CashEnum { NORMAL("正常收费", "1"), DISCOUNT("打折收费", "2"), RETURN("返现收费", "3"); CashEnum(String key, String value) { this.key = key; this.value = value; } private String key; private String value; public String getKey() { return key; } public String getValue() { return value; } }} 该类用于根据不同的收费策略选择合适的处理逻辑,提供计算最终支付金额的功能。
package com.zawl.designpattern.strategy;public class CashConstants { public static final String NORMAL = "NORMAL"; public static final String DISCOUNT = "DISCOUNT"; public static final String RETURN = "RETURN";} 定义了常用的收费类型标识符,供上下文对象使用。
package com.zawl.designpattern.strategy;public class Client { public static void main(String[] args) { CashContext context = new CashContext(CashConstants.RETURN); BigDecimal result = context.getResult(300); System.out.println("最终收费:" + result.toString()); context = new CashContext(CashConstants.NORMAL); result = context.getResult(300); System.out.println("最终收费:" + result.toString()); context = new CashContext(CashConstants.DISCOUNT); result = context.getResult(300); System.out.println("最终收费:" + result.toString()); }} 客户端代码用于创建不同的收费策略上下文,调用计算最终支付金额的方法。
通过以上实现,可以看到策略模式在不同收费场景下的应用效果。具体结果如下:
转载地址:http://ojne.baihongyu.com/