java-策略模式
前言:
需求:同一套系统,使用不同的资源,例如A使用阿里的OSS,B使用腾讯的OSS,使用配置的方式实现动态选择哪个资源
策略模式示例
做个例子:比如去服装店买衣服,普通会员不打折,黄金会员打9折,铂金会员打8折,钻石会员打7折,这样不同的客户价格计算方式不同,这个时候就可以使用策略模式。
// 一个策略接口
public interface IBill {
/**
* 计算账单
* @param money
* @return 应付金额
*/
BigDecimal calculate(BigDecimal money);
}
不同的策略实现不同的实现类
/**
* @author
* @description 普通会员
* @date
*/
@Service("RegularType")
public class RegularMember implements IBill{
@Override
public BigDecimal calculateBill(BigDecimal money) {
//10折
return money.multiply(new BigDecimal(1));
}
}
/**
* @author
* @description 黄金会员
* @date
*/
@Service("GoldType")
public class GoldMember implements IBill{
@Override
public BigDecimal calculateBill(BigDecimal money) {
//9折
return money.multiply(new BigDecimal(0.9)).setScale(2, RoundingMode.HALF_UP);
}
}
/**
* @author
* @description 铂金会员
* @date
*/
@Service("PlatinumType")
public class PlatinumMember implements IBill{
@Override
public BigDecimal calculateBill(BigDecimal money) {
//8折
return money.multiply(new BigDecimal(0.8)).setScale(2, RoundingMode.HALF_UP);
}
}
测试接口
@RestController
public class IBillStrategyContext {
@Autowired
private ApplicationContext applicationContext;
/**
* 计算账单
* @param memberType
* @param money
* @return 应付金额
*/
@GetMapping("calculate")
public BigDecimal calculateBill(@RequestParam("memberType") String memberType,
@RequestParam("money") BigDecimal money){
IBill bean = applicationContext.getBean(memberType, IBill.class);
return bean.calculateBill(money);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律