我已經爲一項任務編寫了這段代碼,我希望它能夠很好地分解。基本上,這是一個簡單的老派計算器的一部分,執行加法,減法,乘法,除法(在執行除法時,應始終顯示提醒)。我們需要爲每個操作分別設置不同的類(加法,減法,乘法,除法,但我已經介紹了一個 - 提醒)。你有什麼建議嗎?或者你在我對Java泛型概念的理解上看到一些差距?更好地構建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!");
}
}
}
}
http://codereview.stackexchange.com/ – Tom
將'ADD'等改爲一個枚舉,並在枚舉上實現特定於操作符的邏輯作爲方法。 –