策略模式:一系列的算法 将每个算法封装起来 使他们可以相互替换 需要设计一个接口 为这个一系列实现类提供统一的方法 多个实现类实现该接口 设计一个抽象类 提供辅助函数 在使用的过程中可以适配改换算法
interface ICalculator {
int calcutor(String exp);
}
abstract class AbstractCalculator {
public int[] spilt(String exp, String opt) {
String[] array = exp.split(opt);
int[] ints = new int[2];
ints[0] = Integer.parseInt(array[0]);
ints[1] = Integer.parseInt(array[1]);
return ints;
}
}
class Plus extends AbstractCalculator implements ICalculator {
@Override
public int calcutor(String exp) {
int[] spilts = spilt(exp, "\\+");
return spilts[0] + spilts[1];
}
}
class Minus extends AbstractCalculator implements ICalculator {
@Override
public int calcutor(String exp) {
int[] spilts = spilt(exp, "\\-");
return spilts[0] - spilts[1];
}
}
class Multiply extends AbstractCalculator implements ICalculator {
@Override
public int calcutor(String exp) {
int[] spilts = spilt(exp, "\\*");
return spilts[0] * spilts[1];
}
}
class CalcuteHandler {
private ICalculator iCalculator;
public CalcuteHandler(ICalculator iCalculator) {
this.iCalculator = iCalculator;
}
public ICalculator getiCalculator() {
return iCalculator;
}
public void setiCalculator(ICalculator iCalculator) {
this.iCalculator = iCalculator;
}
public int calcutor(String exp) {
return iCalculator.calcutor(exp);
}
}
class Test {
public static void main(String[] args) {
String exp = "10*8";
CalcuteHandler calcuteHandler = new CalcuteHandler(new Multiply());
int calcutor = calcuteHandler.calcutor(exp);
System.out.println(calcutor);
exp = "10-8";
calcuteHandler.setiCalculator(new Minus());
calcutor = calcuteHandler.calcutor(exp);
System.out.println(calcutor);
}
}
输出的结果为: