publicCalculator(int a, int b, Operation operation) { this.a = a; this.b = b; this.operation = operation; }
publicvoidcompute() { switch (operation) { case ADD: result = a + b; break; case SUB: result = a - b; break; case MUL: result = a * b; break; case DIV: if (b == 0) { thrownewIllegalArgumentException("除数为0"); } result = a / b; break; } System.out.println("计算:" + a + getOp() + b + "=" + result); }
publicintgetResult() { return result; }
@Override public String toString() { Stringop= getOp(); return a + op + b + "=" + result; }
private String getOp() { Stringop=null; switch (operation) { case ADD: op = "+"; break; case SUB: op = "-"; break; case MUL: op = "*"; break; case DIV: op = "/"; break; } return op; } }
//这才是用户调用的接口 publicvoidcompute(Calculator.Operation operation, int a, int b) { ComputeCommandcomputeCommand=newComputeCommand(newCalculator(a, b, operation)); computeCommand.execute(); undos.add(computeCommand); } }