【发布时间】:2016-06-11 12:40:54
【问题描述】:
我已经为一个作业编写了这段代码,我希望它能够被很好地分解。基本上,这是一个简单的老式计算器的一部分,用于执行加法、减法、乘法、除法(执行除法时,应始终显示提示)。我们需要为每个操作(加法、减法、乘法、除法)设置单独的类,但我已经介绍了另外一个 - 提醒)。您有什么建议,或者您是否发现我对 Java 泛型概念的理解存在一些差距?
public class Logic
implements LogicInterface {
private final int ADDITION = 1;
private final int SUBTRACTION = 2;
private final int MULTIPLICATION = 3;
private final int DIVISION = 4;
/**
* Reference to the Activity output.
*/
protected ActivityInterface mOut;
/**
* Constructor initializes the field.
*/
public Logic(ActivityInterface out){
mOut = out;
}
/**
* Perform the @a operation on @a argumentOne and @a argumentTwo.
*/
public void process(int argumentOne,
int argumentTwo,
int operation){
OperationsInterface operationsInterface =null;
if(operation==ADDITION)
{
operationsInterface = new Add();
}
else if(operation==SUBTRACTION)
{
operationsInterface = new Subtract();
}
else if(operation==MULTIPLICATION)
{
operationsInterface = new Multiply();
}
else
{
operationsInterface = new Divide();
}
if(argumentTwo==0 && operation == DIVISION) {
mOut.print("You cannot divide by zero!");
}
else {
try {
//get the result
int result = operationsInterface.process(argumentOne, argumentTwo);
mOut.print(String.valueOf(result));
//add the reminder to the output in case we are performing division
if (operation == DIVISION) {
operationsInterface = new Reminder();
mOut.print(result + " R: " + String.valueOf(operationsInterface.process(argumentOne, argumentTwo)));
}
}
catch (Exception exception)
{
mOut.print("Something went wrong!");
}
}
}
}
【问题讨论】:
-
将
ADD等改成一个枚举,并将特定于操作符的逻辑实现为枚举上的方法。
标签: java android generics polymorphism refactoring