我试图以不同的方式实现Wikipedia中显示的策略模式示例。这是我的想法:
/** My wrapper idea for implementing the strategy pattern **/
class Calculator{
static public final int OPTION_ADD = 1;
static public final int OPTION_SUBTRACT = 2;
static public final int OPTION_MULTIPLY = 3;
//The following objects are the same as the ones in Wikipedia
private Add add;
private Subtract subtract;
private Multiply multiply;
public Calculator(){
add = new Add();
subtract = new Subtract();
multiply = new Multiply();
}
public int execute(int a, int b, int option){
switch(option){
case OPTION_ADD:
return add.execute(a, b);
case OPTION_SUBTRACT:
return subtract.execute(a, b);
case OPTION_MULTIPLY:
return multiply.execute(a, b);
}
return -1;
}
}
class StrategyStatic {
public static void runStrategy() {
Calculator calculator = new Calculator();
int resultA = calculator.execute(3,4,Calculator.OPTION_ADD);
int resultB = calculator.execute(3,4,Calculator.OPTION_SUBTRACT);
int resultC = calculator.execute(3,4,Calculator.OPTION_MULTIPLY);
System.out.println("Result A : " + resultA );
System.out.println("Result B : " + resultB );
System.out.println("Result C : " + resultC );
}
}
然而,当我运行代码8亿次时,维基百科的代码片段的速度提高了3%。为什么呢?
创建和销毁对象Add,Subtract和Multiply比只创建一个只包含一种类型实例的包装对象并在运行时根据所选选项调用每个方法更快?