策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,
属于辅助类),提供辅助函数。策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种
算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
1. public interface ICalculator {
2. public int calculate(String exp);
3. }
4. ---------------------------------------------------------
5. public class Minus extends AbstractCalculator implements ICalculator {
6.
7. @Override
8. public int calculate(String exp) {
9. int arrayInt[] = split(exp, "-");
10. return arrayInt[0] - arrayInt[1];
11. }
12. }
13. ---------------------------------------------------------
14. public class Plus extends AbstractCalculator implements ICalculator {
15.
16. @Override
17. public int calculate(String exp) {
18. int arrayInt[] = split(exp, "\\+");
19. return arrayInt[0] + arrayInt[1];
20. }
21. }
22. --------------------------------------------------------
23. public class AbstractCalculator {
24. public int[] split(String exp, String opt) {
25. String array[] = exp.split(opt);
26. int arrayInt[] = new int[2];
27. arrayInt[0] = Integer.parseInt(array[0]);
28. arrayInt[1] = Integer.parseInt(array[1]);
29. return arrayInt;
30. }
31. }
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. } |
|