0


策略设计模式

引子

publicclassDemoTest{publicstaticintcal(Integer num1,Integer num2,String op){switch(op){case"+":return num1 + num2;case"-":return num1 - num2;case"*":return num1 * num2;case"/":return num1 / num2;case"%":return num1 % num2;default:thrownewRuntimeException("operation error");}}publicstaticvoidmain(String[] args){System.out.println(cal(10,5,"+"));System.out.println(cal(10,5,"-"));System.out.println(cal(10,5,"*"));System.out.println(cal(10,5,"/"));System.out.println(cal(10,5,"%"));}}

存在问题:每次增加功能,都需要修改已有的代码

基本实现

  • 类图在这里插入图片描述
  • 接口
publicinterfaceCalculator{intcal(Integer num1,Integer num2);}
  • 上下文
publicclassCalculatorContext{privateCalculator calculator;publicCalculatorContext(){}publicCalculatorContext(Calculator calculator){this.calculator = calculator;}publicvoidsetCalculator(Calculator calculator){this.calculator = calculator;}publicintcal(Integer num1,Integer num2){int res = calculator.cal(num1, num2);return res;}}
  • 具体功能实现类
publicclassAddCalculatorimplementsCalculator{@Overridepublicintcal(Integer num1,Integer num2){return num1+num2;}}publicclassSubCalculatorimplementsCalculator{@Overridepublicintcal(Integer num1,Integer num2){return num1 - num2;}}publicclassMultiCalculatorimplementsCalculator{@Overridepublicintcal(Integer num1,Integer num2){return num1*num2;}}
  • 测试代码:
publicclassDemoTest{publicstaticvoidmain(String[] args){CalculatorContext context =newCalculatorContext();

        context.setCalculator(newAddCalculator());System.out.println(context.cal(10,5));

        context.setCalculator(newSubCalculator());System.out.println(context.cal(10,5));

        context.setCalculator(newMultiCalculator());System.out.println(context.cal(10,5));}}

基于lambda实现

  • 原理在这里插入图片描述
  • 代码
publicclassDemoTest{publicstaticintfun(Integer num1,Integer num2,BiFunction<Integer,Integer,Integer> bf){Integer res = bf.apply(num1, num2);return res;}publicstaticvoidmain(String[] args){System.out.println(fun(100,20,(num1, num2)-> num1 + num2));System.out.println(fun(100,20,(num1, num2)-> num1 - num2));System.out.println(fun(100,20,(num1, num2)-> num1 * num2));System.out.println(fun(100,20,(num1, num2)-> num1 / num2));}}

本文转载自: https://blog.csdn.net/lianghecai52171314/article/details/123688823
版权归原作者 梁云亮 所有, 如有侵权,请联系我们删除。

“策略设计模式”的评论:

还没有评论