UP | HOME

策略模式

Table of Contents

策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户

UML

strategy.png

Java

  • 定义算法接口:
    public interface ICalculator {
        int calculate(String exp);
    }
    
  • 抽象类,实现通用辅助方法:
    public abstract class AbstractCalculator implements ICalculator {
        public int[] split(String exp, String opt) {
            String array[] = exp.split(opt);
            int arrayInt[] = new int[2];
            arrayInt[0] = Integer.parseInt(array[0]);
            arrayInt[1] = Integer.parseInt(array[1]);
            return arrayInt;
        }
    }
    
  • 实现三种算法:
    public class Plus extends AbstractCalculator {
        public int calculate(String exp) {
            int arrayInt[] = split(exp, "\\+");
            return arrayInt[0] + arrayInt[1];
        }
    }
    
public class Multiply extends AbstractCalculator {
    public int calculate(String exp) {
        int arrayInt[] = split(exp, "\\*");
        return arrayInt[0] * arrayInt[1];
    }
}
public class Minus extends AbstractCalculator {
    public int calculate(String exp) {
        int arrayInt[] = split(exp, "-");
        return arrayInt[0] - arrayInt[1];
    }
}
  • 测试类:
    public class CalculatorTest {
        public static void main(String[] args) {
            String exp = "2+8";
            ICalculator cal = new Plus();
            int result = cal.calculate(exp);
            System.out.println(result);
        }
    }
    
  • 测试结果:
    10
    

Scheme

  • 具体算法作为函数参数传入:
    (define calculator
      (lambda (operator)
        (lambda (op1 op2)
          (operator op1 op2))))
    
  • 测试结果:
((calculator +) 8 2) ;; => 10
((calculator -) 8 2) ;; => 6
((calculator *) 8 2) ;; => 16

Next:模板模式

Home:目录