策略模式

本文章,摘抄自:2018黑马程序最新面试题汇总

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

需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数。

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

1 public interface ICalculator {
2     public int calculate(String exp);
3 }
1 public class Minus extends AbstractCalculator implements ICalculator {
2 
3     @Override
4     public int calculate(String exp) {
5         int arrayInt[] = split(exp, "-");
6         return arrayInt[0] - arrayInt[1];
7     }
8 
9 }
1 public class Plus extends AbstractCalculator implements ICalculator {
2 
3     @Override
4     public int calculate(String exp) {
5         int arrayInt[] = split(exp, "\+");
6         return arrayInt[0] + arrayInt[1];
7     }
8 
9 }
1 public 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 }

测试方法:

 1 public class StrategyTest {
 2 
 3     @Test
 4     public void test() {
 5         String exp = "2+8";
 6         ICalculator calculator = new Plus();
 7         int result = calculator.calculate(exp);
 8         System.out.println(result);
 9     }
10 }
原文地址:https://www.cnblogs.com/ffeiyang/p/9542759.html