本文源码:GitHub·点这里 || GitEE·点这里
一、生活场景
每年双十一,各大电商平台会推出不同的满减策略,当用户的消费金额满一定额度后,会进行减去一定的优惠额度,从而来一波清仓甩卖,使用策略模式来描述该流程。
1public class C01_InScene { 2 public static void main(String[] args) { 3 // 选择满减策略,走相应的计算方式 4 FullReduce strategy = new Full100 (); 5 Payment price = new Payment(strategy); 6 double quote = price.payment(300); 7 System.out.println("最终价格为:" + quote); 8 } 9} 10/** 11 * 付款 12 */ 13class Payment { 14 private FullReduce fullReduce ; 15 public Payment (FullReduce fullReduce){ 16 this.fullReduce = fullReduce ; 17 } 18 public double payment (double totalPrice){ 19 return this.fullReduce.getPayMoney(totalPrice) ; 20 } 21} 22/** 23 * 金额满减接口 24 */ 25interface FullReduce { 26 double getPayMoney (double totalPrice) ; 27} 28/** 29 * 不同的满减策略 30 */ 31class Full100 implements FullReduce { 32 @Override 33 public double getPayMoney(double totalPrice) { 34 if (totalPrice >= 100){ 35 totalPrice = totalPrice-20.0 ; 36 } 37 return totalPrice ; 38 } 39} 40class Full500 implements FullReduce { 41 @Override 42 public double getPayMoney(double totalPrice) { 43 if (totalPrice >= 500){ 44 totalPrice = totalPrice-120.0 ; 45 } 46 return totalPrice ; 47 } 48}
二、策略模式
1、基础概念
策略模式属于对象的行为模式。策略模式中定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化独立于使用算法的客 户端。
2、模式图解

3、核心角色
- 环境角色
持有一个Strategy策略接口角色的引用。
- 抽象策略角色
通常由一个接口或抽象类实现。此角色给出所有的具体策略类要实现的接口。
- 具体策略角色
包装相关的算法或业务流程。
4、源码实现
1public class C02_Strategy { 2 public static void main(String[] args) { 3 Strategy strategy = new ConcreteStrategyB() ; 4 Context context = new Context(strategy) ; 5 context.userMethod(); 6 } 7} 8/** 环境角色类 */ 9class Context { 10 //持有一个具体策略的对象 11 private Strategy strategy; 12 /** 13 * 构造函数,传入一个具体策略对象 14 * @param strategy 具体策略对象 15 */ 16 public Context(Strategy strategy){ 17 this.strategy = strategy; 18 } 19 public void userMethod (){ 20 this.strategy.strategyMethod(); 21 } 22} 23/** 抽象策略类 */ 24interface Strategy { 25 // 策略方法 26 void strategyMethod () ; 27} 28/** 具体策略类 */ 29class ConcreteStrategyA implements Strategy { 30 @Override 31 public void strategyMethod() { 32 System.out.println("策略A方法"); 33 } 34} 35class ConcreteStrategyB implements Strategy { 36 @Override 37 public void strategyMethod() { 38 System.out.println("策略B方法"); 39 } 40}
三、策略模式总结
策略模式的关键是:变化的与不变分离,体现了“对修改关闭,对扩展开放”原则。客户端增加行为不用修改原有代码,只要添加一种策略即可,易于切换、易于理解、易于扩展。策略过多是会导致类数目庞大,变得难以维护。
四、源代码地址
1GitHub·地址 2https://github.com/cicadasmile/model-arithmetic-parent 3GitEE·地址 4https://gitee.com/cicadasmile/model-arithmetic-parent
