策略模式定义了一系列算法,每个算法封装起来,他们可以相互替换,且算法的变化不会影响到使用算法的客户。可以设计一个抽象类提供辅助。
package WHP; public interface ICalculator { public int calculate(String exp); }
1 package WHP; 2 3 public class AbstractCalculator { 4 5 public int[] split(String exp, String opt) { 6 // TODO Auto-generated method stub 7 String array[] = exp.split(opt); 8 int arrayInt[] = new int[2]; 9 arrayInt[0] = Integer.parseInt(array[0]); 10 arrayInt[1] = Integer.parseInt(array[1]); 11 return arrayInt; 12 } 13 }
1 package WHP; 2 3 public class Plus extends AbstractCalculator implements ICalculator { 4 5 public int calculate(String exp) { 6 // TODO Auto-generated method stub 7 int arrayInt[]=split(exp,"\+"); 8 return arrayInt[0]+arrayInt[1]; 9 } 10 }
1 package WHP; 2 3 public class Minus extends AbstractCalculator implements ICalculator { 4 5 public int calculate(String exp) { 6 // TODO Auto-generated method stub 7 int arrayInt[] = split(exp, "-"); 8 return arrayInt[0] + arrayInt[1]; 9 } 10 }