classCalculator {public float add(float a, float b) {return a + b }public float subtract(float a, float b) {return a — b }}
我们像下面这样使用这个类:
Calculator calculator =newCalculator()float sum =calculator.add(10,2) //the value of sum is 12float diff =calculator.subtract(10,2) //the value of diff is 8
classAdditionimplementsOperation {public float compute(float a, float b) {return a + b }}classSubtractionimplementsOperation {public float compute(float a, float b) {return a — b }}
classCalculator {public float calculate(float a, float b, Operation operation) {returnoperation.compute(a, b) }}
我们将像下面这样使用我们的新类:
Calculator calculator =newCalculator()Addition addition =newAddition()Subtraction subtraction =newSubtraction()float sum =calculator.calculate(10,2, addition) //the value of sum is 12float diff =calculator.calculate(10,2, subtraction) //the value of diff is 8
现在如果我们需要添加乘法,我们将创建这样的一个乘法运算类:
classMultiplicationimplementsOperation {public float compute(float a, float b) {return a * b }}
然后通过添加以下内容在上面的示例中使用它:
Multiplication multiplication =newMultiplication()float prod =calculator.calculate(10,2, multiplication) // the value of prod is 20