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