java-策略模式

发布时间 2023-11-24 09:28:53作者: 鱼被困在了水里

使用原因:

  需求:同一套系统,使用不同的资源,例如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);
	}

}