且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

设计模式——13策略模式(strategy)

更新时间:2022-05-31 00:50:14

13、策略模式(strategy)
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数。

图中ICalculator提供同意的方法,
AbstractCalculator是辅助类,提供辅助方法,接下来,依次实现下每个类:
首先统一接口:
[java] view plaincopy

  1. public interface ICalculator {
  2. public int calculate(String exp);
  3. }
    辅助类:

[java] view plaincopy

  1. public abstract class AbstractCalculator {
  2. public int[] split(String exp,String opt){
  3. String array[] = exp.split(opt);
  4. int arrayInt[] = new int[2];
  5. arrayInt[0] = Integer.parseInt(array[0]);
  6. arrayInt[1] = Integer.parseInt(array[1]);
  7. return arrayInt;
  8. }
  9. }
    三个实现类:

[java] view plaincopy

  1. public class Plus extends AbstractCalculator implements ICalculator {
  2. @Override
  3. public int calculate(String exp) {
  4. int arrayInt[] = split(exp,"\+");
  5. return arrayInt[0]+arrayInt[1];
  6. }
  7. }
    [java] view plaincopy
  8. public class Minus extends AbstractCalculator implements ICalculator {
  9. @Override
  10. public int calculate(String exp) {
  11. int arrayInt[] = split(exp,"-");
  12. return arrayInt[0]-arrayInt[1];
  13. }
  14. }
    [java] view plaincopy
  15. public class Multiply extends AbstractCalculator implements ICalculator {
  16. @Override
  17. public int calculate(String exp) {
  18. int arrayInt[] = split(exp,"\*");
  19. return arrayInt[0]*arrayInt[1];
  20. }
  21. }
    简单的测试类:

[java] view plaincopy

  1. public class StrategyTest {
  2. public static void main(String[] args) {
  3. String exp = "2+8";
  4. ICalculator cal = new Plus();
  5. int result = cal.calculate(exp);
  6. System.out.println(result);
  7. }
  8. }
    输出:10

策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。