提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、策略模式是什么?
策略模式属于对象的行为模式。其用意是针对不同的算法,将每一个算法封装到具有共同接口的独立的类中,从而使它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
二、策略模式使用
1.创建策略接口
代码如下(示例):
public interface DiscountStrategy {
/**
* 打折
*/
long discounts(long money);
}
2.创建接口实现类
代码如下(示例):
/**
* 支付宝支付
*/
@Slf4j
public class AlipayPayStrategy implements DiscountStrategy {
/**
* 打折
* 微信支付满50减1.5元
*/
@Override
public long discounts(long money) {
long price = money - 150;
log.info("支付宝优惠后需支付价格 price={}", price);
//正常业务中需进行很多操作,不仅仅是这些.如像支付宝请求支付接口等等.
return price;
}
}
/**
* 银联支付
*/
@Slf4j
public class UnionpayPayStrategy implements DiscountStrategy {
/**
* 打折
* 微信支付满50减0.5元
*/
@Override
public long discounts(long money) {
long price = money - 50;
log.info("银联优惠后需支付价格 price={}", price);
//正常业务中需进行很多操作,不仅仅是这些.如像银联请求支付接口等等.
return price;
}
}
/**
* 微信支付
*/
@Slf4j
public class WeChatPayStrategy implements DiscountStrategy {
/**
* 打折
*
* @param money 金额
* 微信支付满50减1元
*/
@Override
public long discounts(long money) {
long price = money - 100;
log.info("微信优惠后需支付价格 price={}", price);
//正常业务中需进行很多操作,不仅仅是这些.如像微信请求支付接口等等.
return price;
}
}
3、创建Context类
Context类:这个类其实是做上下文操作的,当上下文特别简单的时候,就显示不到他的作用了,例如对策略执行完的数据处理等等,都是需要写到context的。将相关的属性或一些公共的方法封装到上下文中。
/**
* Context 上下文切换
*/
@Slf4j
public class PayStrategyContext {
private DiscountStrategy discountStrategy;
public PayStrategyContext(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public long discounts(long money) {
//每单扣除1分钱
money -= 10;
log.info("抽佣后的钱={}", money);
long discounts = discountStrategy.discounts(money);
return discounts;
}
}
4、运行策略
public class StrategyTest {
public static void main(String[] args) {
long money = 1000;
//支付宝
PayStrategyContext payStrategyContext = new PayStrategyContext(new AlipayPayStrategy());
//银联
//PayStrategyContext payStrategyContext = new PayStrategyContext(new UnionpayPayStrategy());
//微信
//PayStrategyContext payStrategyContext = new PayStrategyContext(new WeChatPayStrategy());
long price=payStrategyContext.discounts(money);
System.err.println("优惠后: " + price);
}
}
结果:
总结
本文首先介绍了策略模式的定义和结构。
优点:算法可以自由切换,扩展性良好,增加一种相似的业务/算法就增加一个策略类就OK,无需改动其它代码。
缺点:策略类的数量增多,每一个策略都是一个类,复用的可能性很小、类数量增多,所有的策略类都需要对外暴露,上层模块必须知道有哪些策略,然后才能决定使用哪一个策略。
下文将讲解 策略+工厂如何搭配使用。